将图像从 iOS 应用程序上传到 php --- 不太正确 --- 我错过了什么?

2024-03-31

首先,我知道这个问题已经被问过一千次了。我再次询问,因为我已经尝试了其他示例中的解决方案,但它们对我不起作用,我不知道为什么。每个人的方法似乎都略有不同。

NSData *imageData =  UIImagePNGRepresentation(form.image);
NSURL *url = [NSURL URLWithString:@"myscript.php"];
NSMutableString *postParams = [[NSMutableString alloc] initWithFormat:@"&image=%@", imageData]];

NSData *postData = [postParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [[NSString alloc] initWithFormat:@"%d", [postData length]];

NSMutableURLRequest *connectRequest = [[NSMutableURLRequest alloc] init];
[connectRequest setURL:url];
[connectRequest setHTTPMethod:@"POST"];
[connectRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[connectRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//[connectRequest setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
[connectRequest setHTTPBody:postData];

NSData *receivedData;
NSDictionary *jsonData;

NSURLConnection *connectConnection = [[NSURLConnection alloc] initWithRequest:connectRequest delegate:self];

NSError *error = nil;

if (!connectConnection) {
    receivedData = nil;
    NSLog(@"The connection failed!");
} else {
    NSLog(@"Connected!");
    receivedData = [NSURLConnection sendSynchronousRequest:connectRequest returningResponse:NULL error:&error];
}

if (!receivedData) {
    NSLog(@"Data fetch failed: %@", [error localizedDescription]);
} else {
    NSLog(@"The data is %lu bytes", (unsigned long)[receivedData length]);
    NSLog(@"%@", receivedData);

    if (NSClassFromString(@"NSJSONSerialization")) {
        id object = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];

        if (!object) {
            NSLog(@"JSON Serialization failed: %@", [error localizedDescription]);
        }

        if ([object isKindOfClass:[NSDictionary class]]) {
            jsonData = object;
            NSLog(@"json data: %@", jsonData);
        }
    }
}

目前我正在 postParams 中传递 NSData 并使用此 php 脚本:

if (isset($_POST['image']) && !empty($_POST['image'])) {

     if (file_put_contents('images/test.png', $_POST['image'])) {
           echo '{"saved":"YES"}'; die();
     } else {
           echo '{"saved":"NO"}'; die();     
     }
}

这是将数据保存到文件中,但我无法打开它,因为它已损坏或类似的情况。这几乎是最后的努力,我真的没想到它会以这种方式工作,但到目前为止,它已经非常接近正确的结果了。

我尝试过使用各种内容标题/边界/$_FILES/enctype 内容类型方法,但我什至无法将其正确发送到脚本。

  • 顺便说一句,我不只是发送图像数据,我还在 postParams 中发布其他值,这些值只是字符串、整数等。

有谁对此有任何建议或知道任何好的来源吗?

感谢您提供的任何帮助。


遵循以下答案中给出的建议后的当前状态(还有来自程序其他部分的进一步信息):

图像的初始捕获:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [self.view endEditing:YES];

    __unused form *form = self.form;

    form.signature = self.signatureDrawView.bp;

    UIGraphicsBeginImageContext(self.signatureDrawView.bounds.size);
    [self.signatureDrawView.layer renderInContext:UIGraphicsGetCurrentContext()];
    campaignForm.signatureImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

其中signatureDrawView是UIView,form.signature是UIBezierpath。


then...

NSData *sigImage =  UIImagePNGRepresentation(campaignForm.signatureImage);

它被传递给以下函数:

- (void)uploadImage:(NSData *)imageData
{
    NSMutableURLRequest *request;
    NSString *urlString = @"https://.../upload.php";
    NSString *filename = @"uploadTest";
    request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:imageData]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString;
    returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", returnString);
}

upload.php 看起来像:

    if ($_FILES["file"]["error"] > 0) {
        echo '{"file":"'.$_FILES['file']['error'].'"}';
        die();
    } else {
        $size = $_FILES["file"]["size"] / 1024;
        $upload_array = array(
                    "Upload"=>$_FILES["file"]["name"],
                    "Type"=>$_FILES["file"]["type"],
                    "Size"=>$size,
                    "Stored in"=>$_FILES["file"]["tmp_name"]
                    );
        //echo json_encode($upload_array);
        if (move_uploaded_file($_FILES["file"]["tmp_name"], "signatures/" . $_FILES["file"]["name"])) {
            echo '{"success":"YES"}';
            die();  
        } else { 
            echo '{"success":"NO"}';
            die();  
        }
        die();
    }

这给了我 {success:NO} 输出,并且 $upload_array 转储显示空值。


输入以下代码,希望您能得到帮助

NSData *myData=UIImagePNGRepresentation([self.img image]);
NSMutableURLRequest *request;
NSString *urlString = @"http://xyzabc.com/iphone/upload.php";
NSString *filename = @"filename";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:myData]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString;
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将图像从 iOS 应用程序上传到 php --- 不太正确 --- 我错过了什么? 的相关文章

  • 使用 iPhone 摄像头检测心率 [重复]

    这个问题在这里已经有答案了 可能的重复 使用摄像头检测心率 https stackoverflow com questions 9274027 detecting heart rate using the camera 我正在研究 iOS
  • Laravel/00webhost 错误 404。在此服务器上找不到请求的 URL

    1 将我的文件上传到 000webhost 我将公用文件夹中的所有文件放置到公共 html然后我创建了一个名为laravel我在那里上传了所有其他文件 这是我的目录结构 laravel app 引导程序 config 公共 html 索引
  • 两者都实现了类。将使用两者之一

    我有一个项目 它具有使用 SocketRocket 的依赖项 通过 CocoaPods 安装 并从 HeapAnalytics 导入了静态库 显然 HeapAnalytics 库已经使用了 SocketRocket 编译时没有出现错误 但在
  • 使用 mongoose 通过 React 应用程序将图像上传到 mongodb 数据库

    我正在为找到的对象创建一个反应应用程序 我想允许用户上传这些对象的照片 我尝试使用 axios 通过 post 请求将图像发送到猫鼬服务器 但它不起作用 这就是我如何将图像存储在带有预览的 React 组件中 handleImage eve
  • 如何自动缩放mapView以显示叠加层

    我可以在 mapView 上绘制多边形 但是我需要找到多边形并手动缩放它 有没有办法自动执行此过程 例如调整中心多边形 我浏览过互联网并阅读了一些相关文章 其中大多数都是基于折线和点的 任何形式的帮助将不胜感激 因为我正在寻找解决方案一段时
  • 从 php 执行 bash 脚本并立即输出回网页

    我有一组 bash 和 Perl 脚本 开发在 Linux Box 上部署所需的目录结构 可选 从svn导出代码 从这个源构建一个包 这在终端上运行良好 现在 我的客户请求此流程的 Web 界面 例如 某些页面上的 创建新包 按钮将一一调用
  • 如何在同一 PHP 页面上多次使用 mysqli fetch_assoc() 和准备好的语句?

    有没有办法启用fetch assoc 在同一页上多次使用准备好的语句 data conn gt prepare SELECT FROM some table WHERE id data gt bind param i id data gt
  • 合并 2 个数组并合并数字键的结果

    我有 2 个数组 我希望通过每个数字键将其中合并 分组在一起 例如 Array1 2009 gt 131 2008 gt 940 2007 gt 176 2006 gt 1 Array2 2008 gt 9 2007 gt 3 我希望输出是
  • iOS - NSNotificationCenter 多个UIKeyboard通知

    我有两个视图控制器 我们称它们为 A 和 B 1 在 A 中 我显示一个包含文本字段的 popOver 2 B中有一个UITextView用于简单的文本编辑 我必须管理 A 和 B 中的键盘才能滚动键盘隐藏的内容 我知道如何重新定位内容 我
  • 当我使用 session_start() 时,Xampp 7.0.1 Apache 崩溃

    当我在 PHP 中使用 session start 启动会话时 我的 Apache 服务器停止工作 我正在使用 Windows 版 Xampp 7 0 1 我的配置文件如下所示 即使我把它放在文件的第一行 它也不起作用 有人知道如何解决这个
  • 正在使用 PIL 保存损坏的图像

    我遇到一个问题 操作图像像素导致保存损坏的图像 因此 我使用 PIL 打开图像 然后将其转换为 NumPy 数组 image Image open myimage png np image np asarray image 然后 我转置图像
  • 从 android 简单上传到 S3

    我在网上搜索了从 android 上传简单文件到 s3 的方法 但找不到任何有效的方法 我认为这是因为缺乏具体步骤 1 https mobile awsblog com post Tx1V588RKX5XPQB TransferManage
  • ACL授权失败后ZF3重定向

    我有一个带有 ACL 的新 ZF3 应用程序 现在 我需要在未经授权的访问的情况下重定向到错误页面 例如 403 我认为最好的方法是触发一个事件 然后捕获它 但我失败了 全部都在我的用户模块中Module php 摘录 namespace
  • php date_parse("2010 年 2 月") 给出日期 == 1

    当没有日期时 我将其称为 date parse 中的错误 d date parse Feb 2010 会给 d day 1 请参阅对此的评论date parse 手册页 http php net manual en function dat
  • PHP LDAP 查询获取特定安全组的成员

    我正在努力让 LDAP 查询工作来为我提供安全组的成员 我们的活动目录结构设置为 DC domain DC co dc uk然后 我们有一个名为 公司用户 的 OU 其中有一个用于 IT 和标准的 OU 在这些中我们创建了用户 所以我被设置
  • PHP 中的encodeURI() ?

    PHP 中是否有一些不编码的encodeURI 函数 我现在用这个 function encodeURI url http php net manual en function rawurlencode php https develope
  • GMSMapView 中的倒多边形

    我必须在我的 iPhone 项目中使用 Google 地图 并且我正在使用 GMSPolygon 来绘制多边形 但是如何填充地图上除多边形内部之外的所有位置 就像下图一样 谢谢 我玩过你的问题 主要思想是用多边形填充整个地球 然后为您的特定
  • 为什么这评估为 true

    为什么这评估结果为真
  • 使用 MYSQL 将 h:mm pm/am 时间格式插入数据库

    我正在尝试将以 h mm am pm 格式写入的时间插入到存储为标准 DATETIME 格式 hh mm ss 的数据库中 但我不知道如何将发布的时间转换为标准格式所以数据库会接受它 这是我到目前为止一直在尝试的 title POST in
  • 无法将 admob 与 firebase iOS/Android 项目链接

    我有两个帐户 A 和 B A 是在 Firebase 上托管 iOS Android unity 手机游戏的主帐户 B 用于将 admob 集成到 iOS Android 手机游戏中 我在尝试将 admob 分析链接到 Firebase 项

随机推荐