如何使用 post 请求异步将图像上传到 url?
Posted
技术标签:
【中文标题】如何使用 post 请求异步将图像上传到 url?【英文标题】:How to upload image to a url using post request asynchronously? 【发布时间】:2012-12-26 14:49:30 【问题描述】:我必须将图片上传到特定的网址。我必须遵循的规范是: 1.方法应该是post 2. 图片必须使用多部分 HTTP 内容类型上传 3. HTTP 字段的名称应为“uploadingTheFile”。 4. 多部分数据应该有文件名。 5.图片内容类型应在以下-jpeg,jpg,png,gif之间
我想使用 NSURLConnection 异步上传。我认为我无法以正确的方式设置请求中的参数。我得到的状态代码为 200,这表明我的 NSURLConnection 委托方法没有问题。我正在尝试的代码是:
NSString *stringBoundary=@"0xKhtmlbOuNdArY";
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary] forHTTPHeaderField:@"uploadfile"];
NSMutableData *postBody = [NSMutableData data];
NSData *imageData=UIImagePNGRepresentation([UIImage imageNamed:@"IMG_0215.JPG"]);
//[postBody appendData:imageData];
[postBody appendData:[@"Content-Disposition: form-data; name=\"data;filename=\"media.png\"\"\r\n" 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",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection)
self.data = [NSMutableData data];
【问题讨论】:
为什么不试试 ASIHttpRequest 方法,它有内置的类可以异步发送数据..... 我处于应用程序完成的后期阶段。现在我想不出只为一项任务使用 ASIHTTP 或其他库。这就是为什么 Gill 不能尝试 ASIHTTP ASIHttpRequest 不再更新,因此您不能在支持 ARC 的情况下使用它 【参考方案1】:我正在使用以下代码,它对我来说工作正常。
NSData *imageData = UIImageJPEGRepresentation(empImgView.image, 90); // convert image in NSData
NSString *urlString = @"http://abc.com/saveimage/Default.aspx"; // your url
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *imgNameString = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",[responseSrting substringWithRange:NSMakeRange(1, responseSrting.length - 2)]];
[body appendData:[[NSString stringWithString:imgNameString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@",returnString);
【讨论】:
他要求异步的方式来做到这一点【参考方案2】:在这里你可以学习如何使用afnetworking上传图片
https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
【讨论】:
【参考方案3】:您可以使用AFNetworking(它是开源的),这是对我有用的代码。这是针对 AFNetworking 3.0 版本的。
NSString *serverUrl = [NSString stringWithFormat:@"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:serverUrl parameters:nil error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress)
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^
//Update the progress view
LLog(@"progres increase... %@ , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
);
completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
if (error)
NSLog(@"Error: %@", error);
else
NSLog(@"Success: %@ %@", response, responseObject);
];
[uploadTask resume];
【讨论】:
以上是关于如何使用 post 请求异步将图像上传到 url?的主要内容,如果未能解决你的问题,请参考以下文章