使用curl - ios上传图片

时间:2014-10-16 07:39:14

标签: objective-c curl nsurlconnection image-uploading nsmutabledata

我正在将图片上传到后端。

CURL命令:

curl -i -X POST -F filedata =@file_logo.jpg http://upload.com/projects/
      媒体/ add_image /8分之44

我使用以下代码:

  NSData *editedImage = [NSData dataWithData:UIImagePNGRepresentation(app.ret)];
  NSString *urlString =@"http://upload.com/projects/  
  media/add_image/44/8";
  NSURL *url = [NSURL URLWithString:urlString];
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
                                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                        timeoutInterval:60];

[request setHTTPMethod:@"POST"];
NSString *curlData = @"filedata=";

NSString *boundary =  @"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSMutableData *body = [NSMutableData data];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];

[body appendData:[[NSString stringWithFormat:@"%@",curlData]dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"files1", @"1.png"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:editedImage]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[body length]]  forHTTPHeaderField:@"Content-Length"];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:body];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                      delegate:self
                                              startImmediately:NO];
[connection start];

我没有得到任何回应,我在这做什么错? 请帮忙。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

这可能是一个非答案"但是,如果你自己不愿意这样做,我强烈建议AFNetworking进行任何网络任务。