iOS AFNetworking 3.0 上传图片视频到服务器
2016-05-11 本文已影响9338人
刘宇航iOS
.h
typedef NS_ENUM(NSUInteger, ResposeStyle) {
JSON,
XML,
Data,
};
typedef NS_ENUM(NSUInteger, RequestStyle) {
RequestJSON,
RequestString,
RequestDefault
};
.m
- @param url 服务器地址
- @param parameters 字典 token
- @param fileData 要上传的数据
- @param name 服务器参数名称 后台给你
- @param fileName 文件名称 图片:xxx.jpg,xxx.png 视频:video.mov
- @param mimeType 文件类型 图片:image/jpg,image/png 视频:video/quicktime
- @param style 返回的数据类型
- @param progress
- @param success
- @param failure
+ (void)upLoadToUrlString:(NSString *)url parameters:(NSDictionary *)parameters fileData:(NSData *)fileData name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType response:(ResposeStyle)style
progress:(void (^)(NSProgress *))progress success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
//1.获取单例的网络管理对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.根据style 的类型 去选择返回值得类型
switch (style) {
case JSON:
manager.responseSerializer = [AFJSONResponseSerializer serializer];
break;
case XML:
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
break;
case Data:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
break;
default:
break;
}
//3.设置相应数据支持的类型
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"application/json", @"application/x-www-form-urlencoded", nil]];
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:mimeType];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(task, responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(task, error);
}
}];
}
PS:上传图片前,必须先压缩图片,不然图片过大,可能会导致上传失败!
具体上传操作:http://www.jianshu.com/p/29585a416af2