dongyanfeng0546 2014-02-13 19:33
浏览 39
已采纳

从我的iOS上传到我的PHP服务器的图像上挣扎

The code below is used to upload image to a remote server, but for a certain reason it does NOT work for me. When I enter, for example to this page and I use the php form to upload image, it works with no problem. So, concerning the PHP part, there is no single problem and everything is working.

The Question :

What's wrong with that ?

        NSData *imageData = UIImageJPEGRepresentation(self.imageViewer.image, 90);
        NSString *urlString = @"http://example.com/post_image.php";
           [request setHTTPMethod:@"POST"];
                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 *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"
--%@
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\".jpg\"
" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream

" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"
--%@--
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];            
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *picture = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"uploaded picture: %@", picture);
  • 写回答

1条回答 默认 最新

  • dswm97353 2014-02-13 19:50
    关注

    Change the mime type to match what you're actually sending (image/jpeg).

    Delete one of these duplicate lines:

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    

    (and probably at least log the error parameter...)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题