IOS 利用AFN上传图片,支持多张、单张上传

前言:本文主要利用AFN来进行图片上传,支持单张、多张;

个人觉得导致上传失败的原因,大部分情况下都是由于

[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"upload%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
这个方法的参数没有与后台一致导致的。

其中需要跟后台约定的有:

1、name:后台可以通过文件名来获取到相应的图片流;

2、mimeType:更多的是让后台知道你上传的类型;


说白了就是报文头能够让后台识别

NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
    [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
    [mutableHeaders setValue:mimeType forKey:@"Content-Type"];


具体代码如下

#import 

typedef void(^HttpUploadSuccessBlock)(id Json);
typedef void(^HttpUploadFailureBlock)();

@interface HttpTool : NSObject

/**
 *  上传图片(单张)
 *
 *  @param path    路径
 *  @param image   图片
 *  @param params  参数
 *  @param success 成功回调
 *  @param failure 失败回调
 */
+ (void)uploadImageWithPath:(NSString *)path image:(UIImage *)image params:(NSDictionary *)params success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure;

/**
 *  上传图片(多张)
 *
 *  @param path    路径
 *  @param photos  图片数组
 *  @param params  参数
 *  @param success 成功回调
 *  @param failure 失败回调
 */
+ (void)uploadImageWithPath:(NSString *)path photos:(NSArray *)photos params:(NSDictionary *)params success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure;

@end

#import "HttpTool.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"

static AFHTTPSessionManager *manager;

@implementation HttpTool

//为了防止内存泄露
+ (AFHTTPSessionManager *)sharedHttpSession
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 10;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    });
    return manager;
}

#pragma mark 上传单张图片
+ (void)uploadImageWithPath:(NSString *)path image:(UIImage *)image params:(NSDictionary *)params success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure
{
    NSArray *array = [NSArray arrayWithObject:image];
    [self uploadImageWithPath:path photos:array params:params success:success failure:failure];
}

#pragma mark 上传图片
+ (void)uploadImageWithPath:(NSString *)path photos:(NSArray *)photos params:(NSDictionary *)params success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure
{
    [SVProgressHUD showProgress:-1 status:@"正在上传,请稍等."];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPSessionManager *manager = [HttpTool sharedHttpSession];
    [manager POST:path parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {
        for (int i = 0; i < photos.count; i ++) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
            UIImage *image = photos[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"upload%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        MyLog(@"uploadProgress is %lld,总字节 is %lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *resultCode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"result_code"]];
        NSString *resultInfo = [responseObject objectForKey:@"result_info"];
        MyLog(@"resultInfo is %@",resultInfo);
        if ([resultCode isEqualToString:@"1"]) {
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            if (success == nil) return ;
            success(responseObject);
        }else {
            [SVProgressHUD showErrorWithStatus:resultInfo];
            if (failure == nil) return ;
            failure();
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"上传失败"];
        if (failure == nil) return ;
        failure();
    }];
}


你可能感兴趣的:(IOS开发,图片,ios,上传,多张,单张)