文件流上传图片
2017-04-05 本文已影响78人
henu_Larva
FilesStreamUpload.h 文件内:
#import <Foundation/Foundation.h>
@interface FilesStreamUpload : NSObject
+ (FilesStreamUpload *)shareManager;
/**
文件流上传图片
@param infoDic 请求参数体
@param files 图片数据
@param url 接口
@param success_block 上传成功回调
@param fail_block 上传失败回调
*/
- (void)filesStreamUploadImages:(NSMutableDictionary *)infoDic imageFiles:(NSArray *)files url:(NSString *)url successBlock:(void(^)(NSDictionary *responseDic))success_block failBlock:(void (^)(id obj))fail_block;
@end
FilesStreamUpload.m 文件内:
#import "FilesStreamUpload.h"
static FilesStreamUpload * filesStreamManager = nil;
@implementation FilesStreamUpload
+ (FilesStreamUpload *)shareManager {
if (!filesStreamManager) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
filesStreamManager = [[FilesStreamUpload alloc] init];
});
}
return filesStreamManager;
}
- (void)filesStreamUploadImages:(NSMutableDictionary *)infoDic imageFiles:(NSArray *)files url:(NSString *)url successBlock:(void(^)(NSDictionary *responseDic))success_block failBlock:(void (^)(id obj))fail_block {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer new];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain", nil];
NSString *strURL = [NSString stringWithFormat:@"%@%@",BASE_URL,url];
NSString *postURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager POST:postURL parameters:infoDic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (UIImage *image in files) {
NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
[formData appendPartWithFileData:imageData name:@"files" fileName:@"files" mimeType:@"image/jpeg"];
}
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
if (success_block) {
success_block(dic);
}
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"%@",error.localizedDescription);
if (fail_block) {
fail_block(error.localizedDescription);
}
}];
}
@end