图片上传
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", @"video/mp4", nil];
[manager POST:URLString parameters:parameter headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSData *imageData;
//获取图片的 data(判断图片的格式)
if (UIImageJPEGRepresentation(upImage, 1.0)) {
imageData = UIImageJPEGRepresentation(upImage,0.2);
} else if (UIImagePNGRepresentation(upImage)) {
imageData = UIImageJPEGRepresentation(upImage,0.2);
} else {
imageData = nil;
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", dateString];
/*
upImage: 图片文件
name: @“这个很重要,一定要和后端的关键字相匹配,否则出错"
fileName:@"取名,我在这里以时间取名"
*/
[formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
视频上传
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", @"video/mp4", nil];
[manager POST:URLString parameters:parameter headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSData *videoData = [NSData dataWithContentsOfFile:paths];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.mp4", dateString];
/*
upImage: 图片文件
name: @“这个很重要,一定要和后端的关键字相匹配,否则出错"
fileName:@"取名,我在这里以时间取名"
*/
[formData appendPartWithFileData:videoData name:@"file" fileName:fileName mimeType:@"video/mp4"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
大家可以将这些代码进行二次封装,代码更加精简,更加好用
【 微信公众号:aircode 】带你从入门到精通
网友评论