之前项目要做上传方面的,也有研究过图片上传方面的一些知识,用AFNetworking中AFHTTPSessionManager类进行图片的POST请求
//上传图片
+(void)postDataWithUrl:(NSString *)url params:(NSMutableDictionary *)params imageDatas:(NSArray *)images success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/xml",nil]];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (UIImage *image in images) {
// 图片太大会上传不到服务器上面去
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);;
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
/*
此方法参数
1. 要上传的[二进制数据]
2. 对应网站上[upload.php中]处理文件的[字段"file"]
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]
*/
[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"uploadProgress = %@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
// 上传语音
+(void)POSTOneAmrWithUrl:(NSString *)url imageWithName:(NSString *)fileName AmrDatas:(NSData *)amr success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/xml",nil]];
[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:amr name:@"file" fileName: [NSString stringWithFormat:@"%@.amr", fileName] mimeType:@"amr/mp3/wmr"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}