我正在开发一款消息应用程序,用户还可以互相发送图片。
当用户发送多张图片时,我会并行发送它们(在发送第二张图片之前,我不会等待第一张图片完成上传)
搬到之前AFNetworking
我成功地做到了这一点ASIFormDataRequest
,事实上,如果我发送 2 个图像,它们都会并行传输并成功传递给其他用户。
当我尝试使用 AFNetworking 执行此操作时,我遇到了一些奇怪的行为。
我将尝试描述 user1 也向 user2 发送两张图像的情况:
- User1 发送 image1 -> 一切看起来都正常,我可以看到上传进度。
- User1 然后发送 image2 -> 看起来仍然没问题,我可以看到两张图片的上传进度
- image1 上传完成 -> user2 收到损坏的图像,看起来像是 image1 和 image2 的组合!
- image2上传完成->user2成功获取image2
这就是我发送图像的方式
- (void)sendImageMsgWithPath:(NSString *)path
image:(UIImage *)image
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
progress:(void (^)(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
{
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
// create the request
NSURLRequest *request = [[AppClient sharedClient] multipartFormRequestWithMethod:@"POST" path:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:@"image_name" fileName:@"image_name.jpg" mimeType:@"image/jpeg"];
}];
// create the operation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
// set progress block
[operation setUploadProgressBlock:progress];
//set completion blocks
[operation setCompletionBlockWithSuccess:success failure:failure];
// set it to work in background
[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:nil];
// add it to the operations queue
[[AppClient sharedClient] enqueueHTTPRequestOperation:operation];
}
*** 两个图片上传的路径是相同的:
路径=
@“FrontEnd?cmd=sendimage&fromuserid=3&touserid=1&”
它将被添加到 baseURL 以创建完整的 URL:
@""
This are the images I sent:
image1
image2
corrupted image
使用 multipartFormRequest 来使用以下方法:
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormDataProxy>formData))block;
例如这样:
NSURLRequest* request = [[YourHTTPClient sharedHTTPClient] multipartFormRequestWithMethod:@"POST"
path:path
parameters:dict
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data1
name:@"image1"
fileName:@"image1.jpg"
mimeType:@"image/jpeg"];
[formData appendPartWithFileData:data2
name:@"image2"
fileName:@"image2.jpg"
mimeType:@"image/jpeg"];
}
}];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)