最近项目中需实现上传图片和其他数据(例如:用户名、经度、纬度、地址等), 通过post表单提交的需求
结果用AFN请求时报500错误,如图所示:
出现500报错,一般是内部服务器错误,但安卓这边可以成功上传,所以排除服务器的问题。有可能是参数没传对,和安卓仔细校对了几遍参数,发现参数没问题,这我就很纳闷了,服务器没问题、传参也没问题,那问题会出在哪呢?
刚开始以为AFN的问题,后面用 ASIFormDataRequest 请求,还是报500错误。后面多次测试发现,没有设置请求头,即Content-Type字段,添加后,大功告成,如果所示:
完整代码:
NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@%@",[utils getAppUploadMeidaUrl],UploadPIC] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *dictonary = [ASIFormDataRequest requestWithURL:url];
[dictonarysetRequestMethod:@"POST"];
//改用这个方法设置header
NSMutableDictionary *header = [[NSMutableDictionary alloc] init];
[headersetValue:@"multipart/form-data" forKey:@"Content-Type"];
[dictonarysetRequestHeaders:header];
[dictonary setPostValue:[utils getUnitID] forKey:@"unitId"];
[dictonary setPostValue:model.componentsTypeName forKey:@"objName"];//部件名称
[dictonary setPostValue:model.componentsCategory forKey:@"componentsCategory"];//部件大类
[dictonary setPostValue:model.componentsType forKey:@"componentsType"];//部件小类
//上传图片
if(self.arrPic.count) {
for(UIImage*eImage in self.arrPic) {
intx =arc4random() %100;
inty =arc4random() %100;
NSData*imageData=UIImageJPEGRepresentation(eImage,100);
NSString*photoName=[NSStringstringWithFormat:@"%zd-%zd.jpg",x,y];
//照片content
[dictonary addData:imageData withFileName:photoName andContentType:@"image/jpeg" forKey:@"picFile"];
}
}else{
//无照片时,后台规定也必须传 picFile 字段
[dictonary addData:@"" withFileName:@"" andContentType:@"image/jpeg" forKey:@"picFile"];
}
[dictonary buildPostBody];
dictonary.shouldAttemptPersistentConnection=NO;
[dictonary setDelegate:self];
[dictonary setDidFailSelector:@selector(responseFailed)];
[dictonary setDidFinishSelector:@selector(responseComplete:)];
[dictonary setTimeOutSeconds:30];
[dictonary startSynchronous];
请求完成
- (void)responseComplete:(ASIHTTPRequest *)request {
NSLog(@"状态码---%d,状态信息---%@",request.responseStatusCode, request.responseStatusMessage);
NSLog(@"返回数据的长度--%ld",request.responseData.length);
NSLog(@"返回的数据---%@",request.responseString);
//将服务器返回的数据解析为字典
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:Nil];
NSLog(@"dictionary== %@",dictionary);
[SVProgressHUD showSuccessWithStatus:@"上传成功"];
}
请求失败
- (void)responseFailed {
[SVProgressHUD showErrorWithStatus:@"上传失败,请检查网络是否正常"];
}
上面我用了ASIFormDataRequest最终上传成功,如果有童鞋用AFN请求,注意老版本请求时 constructingBodyWithBlock:^(id formData) 会导致崩溃,下载最新的版本即可。下面给出AFN代码:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
manager.requestSerializer= [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"text/json", nil];
[manager POST:[NSString stringWithFormat:@"%@%@",[utils getAppUploadMeidaUrl],ModifyPIC] parameters:dictonary constructingBodyWithBlock:^(id formData) {
if (self.arrPic.count) {
for (UIImage *eImage in self.arrPic) {
int x = arc4random() % 100;
int y = arc4random() % 100;
NSData *imageData=UIImageJPEGRepresentation(eImage,100);
NSString *fileName=[NSString stringWithFormat:@"%zd-%zd.jpg",x,y];
NSString *photoDescribe=@" ";
//照片content
[formData appendPartWithFileData:imageData name:@"picFile" fileName:fileName mimeType:@"image/jpeg"];
}
}
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"responseObject=== %@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"task=== %@",task);
NSLog(@"error=== %@",error);
}];
总结:
1:遇到500报错,首先看下安卓那边是否也是同样的错误,如果都错误,和后台校对请求地址、请求头和参数
2:如果安卓成功上传,但iOS报错,这时候就要仔细检查参数名是否写错,有些参数是必传的,是否没传,请求头是否设置正确等
3:注意,有时候必传参数传了,但为空,打印dict无值,说明还是没传过去,这时候应该对 setValue = @"" 赋空值;
以上就是遇到post表单提交报500错误的总结,如有什么问题,欢迎大家在下方留言指正。
网友评论