```
NSData*imageData;
NSString*mimetype;
//判断下图片是什么格式
if (UIImagePNGRepresentation(image) != nil) {
mimetype =@"image/png";
imageData =UIImagePNGRepresentation(image);
}else{
mimetype =@"image/jpeg";
imageData =UIImageJPEGRepresentation(image,1.0);
}
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
NSString* urlString = [self uploadUserImageUrl];
NSDictionary* dict =@{@"id":Id};
[session POST:urlString parameters:dict constructingBodyWithBlock:^(id formData) {
NSString*str =@"avatar";
NSString * fileName = [[NSString alloc]init];
if (UIImagePNGRepresentation(image) != nil) {
fileName = [NSString stringWithFormat:@"%@.png", str];
}else{
fileName = [NSString stringWithFormat:@"%@.jpg", str];
}
// 上传图片,以文件流的格式
/**
*filedata : 图片的data
*name : 后台提供的字段
*mimeType : 类型
*/
NSString * imagePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
imagePath = [image pathstringByAppendingPathComponent:fileName];
//注意此处一定要用图片的本地全路径,不能只是传文件名
[formData appendPartWithFileData:imageDataname:@"file" fileName:imagePath mimeType:mimetype];
}progress:^(NSProgress*_uploadProgress) {
}success:^(NSURLSessionDataTask* task, id responseObject) {
[self requestSuccessTipWithObject:responseObject];
}failure:^(NSURLSessionDataTask*task,NSError*error) {
NSLog(@"error = %@",error);
//请求发生错误回调
dispatch_async(dispatch_get_main_queue(), ^{
[self requestFailureWithError:error delegate:delegate];
});
}];
```
网友评论