最近在写一个类似朋友圈的页面, 需要多张图片上传, 查了好多资料, 看到这个才给完美解决, 记录下了, 以后好用, 也给有需要的人看看直接上代码
// 基于AFN3.0+ 封装的HTPPSession句柄
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval = 20;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
// 在parameters里存放照片以外的对象
[manager POST:@"http://www.example.com/Project/upload.php" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
// 这里的_photoArr是你存放图片的数组
for (int i = 0; i < _photosArr.count; i++) {
UIImage *image = _photosArr[i];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", dateString];
/*
*该方法的参数
1. appendPartWithFileData:要上传的照片[二进制流]
2. name:对应网站上[upload.php中]处理文件的字段(比如upload)
3. fileName:要保存在服务器上的文件名
4. mimeType:上传的文件的类型
*/
[formData appendPartWithFileData:imageData name:
//这句话是重点, 这样可以解决只能上传一张图片的问题
[NSString stringWithFormat:@"%d-upload",i] fileName:fileName mimeType:@"image/jpeg"]; //
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"---上传进度--- %@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"```上传成功``` %@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"xxx上传失败xxx %@", error);
}];
}
作者:FANTASIED
链接:http://www.jianshu.com/p/a55b0d67dbbf
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。