以前項目要作上傳方面的,也有研究過圖片上傳方面的一些知識,用AFNetworking中AFHTTPSessionManager類進行圖片的POST請求javascript
//上傳圖片php
+(void)postDataWithUrl:(NSString *)url params:(NSMutableDictionary *)params imageDatas:(NSArray *)images success:(void (^)(id response))success failure:(void (^)(NSError *error))failurehtml
{java
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];json
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) {app
for (UIImage *image in images) {post
// 圖片太大會上傳不到服務器上面去網站
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);
}];
}