最近用到图片,视频,语音上传,期间遇到一些问题,在此记载一下。代码如下:
NSString *urlString = [NSString stringWithFormat:@"%@%@%@",kZBServerAdd,zbStyle,requestUrl];
NSError *err;
NSMutableURLRequest *request = [[[AFHTTPRequestSerializer alloc] init]
multipartFormRequestWithMethod:@"POST" URLString:urlString
parameters:paramDic
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:fileData
name:FILE_UPLOAD_NAME
fileName:fileName
mimeType:mimeType];
} error:&err];
request.allowsCellularAccess = YES;
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *jsonStr = [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *JSONDit =
[NSJSONSerialization JSONObjectWithData: [jsonStr dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
if ([[JSONDit objectForKey:@"code"] intValue] == SUCCESS) {
if (successBlock) {
successBlock(JSONDit,[[JSONDit objectForKey:@"code"] integerValue]);
}
}else{
NSLog(@"%@",JSONDit[@"message"]);
if (noDataBlock) {
noDataBlock(JSONDit);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
netFailBlock();
}];
[op start];
需要注意的 是
appendPartWithFileData这个方法的参数:
data:需要上传的数据;
name:部分服务器用来解析的字段。之前我们上传图片是本公司的服务器处理,随便写参数没有影响,但是这次用了阿里云,解析出来就有问题了,需要的数据外面多了一个字典,而这个字典的key就是这个“name”。目前这个地方我传的是@"urls[]"。就不会有外面那个字典了。
fileName:是指上传到服务器的文件名,一般是用时间戳加一些内容,但是一般服务器会替换成服务端的名字规则。尤为重要的是,这个地方需要带后缀,例如:图片就xx.png或者xx.jpg;视频就xx.mp4等;语音就xx.amr或xx.pm3等。如果不带后缀服务器会识别不出来的。
mimeType:编码类型,查看编码类型