我这里用AFNetworking上传图片
报The data couldn’t be read because it isn’t in the correct format.有人帮忙看看是哪里出问题了么?下面是我写的代码。
AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
m.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];
m.requestSerializer = [AFHTTPRequestSerializer serializer];
[m.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
NS_APPDebugLog(@"请求链接:%@/%@", urlString, parametersDic);
[m POST:@"http://59.48.96.118:7001/portal/SI_USR00025/upload.do" parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (int i = 0; i < imagePickerArray.count; i++)
{
UIImage *portraitImg = imagePickerArray[i];
portraitImg = [UIImage scaleToSize:portraitImg];
portraitImg = [portraitImg fixOrientation];
NSData *imageData = [NSData compressImage:portraitImg];
[formData appendPartWithFileData:imageData
name:[NSString stringWithFormat:@"img.img%d", i+1]
fileName:@"image.png"
mimeType:@"image/png"];
}
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"成功");
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"失败");
dispatch_async(dispatch_get_main_queue(),^{failure(error);});
}];
A few questions here:
mime settings have some contradictions:
You have set two types of mime in these two places,
multipart/form-data
和image/png
. Which one is correct? Need to communicate with the backend.Contact the backend, have you received your request? What content is requested? What did he return? This error seems to be usually reported when parsing json. Maybe the background does not return valid json. In addition, your request is to upload multiple files at once. I don’t know if your backend interface supports it. You can try uploading only one picture.
There is no need to adjust the AFNetworking block
dispatch_async(dispatch_get_main_queue()...
It has already helped you return to the main thread for execution.Can I print out the data of imageData?
Have you solved it?
I also encountered the report The data couldn’t be read because it isn’t in the correct format.
But in fact the image was uploaded successfully
Client code: - (IBAction)upload:(id)sender {
[manager POST:url3 parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
}
Backend code (python):
class receive(restful.Resource):
api.add_resource(receive, '/upload', methods=['POST'])