使用AFNetworking
//上传图片至服务器后台
-
(void)transportImgToServerWithImg:(UIImage *)img{
NSData *imageData;
NSString *mimetype;
//判断下图片是什么格式
if (UIImagePNGRepresentation(img) != nil) {
mimetype = @“image/png”;
imageData = UIImagePNGRepresentation(img);
}else{
mimetype = @“image/jpeg”;
imageData = UIImageJPEGRepresentation(img, 1.0);
}NSString *urlString =@"http://xxx";
NSDictionary *params = @{
@“Token”😡“123”};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:urlString parameters:params headers:@{@“Content-Type”😡“multipart/form-data”} constructingBodyWithBlock:^(id _Nonnull formData) {
NSString str = @“avatar”;
NSString fileName = [[NSString alloc] init];
if (UIImagePNGRepresentation(img) != nil) {
fileName = [NSString stringWithFormat:@"%@.png", str];
}else{
fileName = [NSString stringWithFormat:@"%@.jpg", str];
}
// 上传图片,以文件流的格式
/
*filedata : 图片的data
*name : 后台的提供的字段
*mimeType : 类型
*/
[formData appendPartWithFileData:imageData name:str fileName:fileName mimeType:mimetype];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@“上传图片成功:%@”,responseObject);} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"上传图片失败,失败原因是:%@", error); }];
}