我正在开发一个消息传递应用程序,用户也可以相互发送图片 当用户发送多张图片时,我会并行发送它们(我发送第二张图片之前不要等第一张图片完成上传)
在转移到AFNetworking
之前,我成功地使用ASIFormDataRequest
执行了此操作,实际上,如果我发送了2张图像,则它们都会并行传输并成功传送给其他用户。
当我尝试使用AFNetworking时,我会遇到一些奇怪的行为 我将尝试描述user1发送两个图像的情况user2:
这是我发送图片的方式
- (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];
}
***两张图片上传的路径都是一样的:
路径= @ “前端CMD = sendimage&安培; fromuserid = 3及touserid = 1&安培;”
它将被添加到baseURL以创建完整的URL:
@ “http://somename.myftp.org:8080/web_proj/FrontEnd?cmd=sendimage&fromuserid=3&touserid=1”
这是我发送的图像:
此搜索
IMAGE2
图片已损坏
答案 0 :(得分:1)
在方法下面使用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"];
}
}];
答案 1 :(得分:1)
如何创建传递到sendImageMsgWithPath:方法的UIImage对象?你是使用imageWithData :(或类似的)创建它们?如果是这样,我在尝试重用NSMutableData时遇到过类似的问题。即使在您创建UIImage之后,子系统仍然需要在以后读取该数据。如果你已经重用了那个NSMutableData,那么图像就会被破坏。
如果是这种情况,我建议您使用新的NSMutableData来创建每个UIImage。