利用AFN以表单的形式上传图片

+ (void)uploadWithUrl:(NSString *)url params:(NSDictionary *)params imageData:(NSData *)imageData success:(void (^) id response))success fail:(void (^) (NSError *error))failure {
    
    AFHTTPSessionManager *manager = [self manager];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"enctype"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat   = @"YYYY-MM-dd-hh:mm:ss:SSS";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        /*
         此方法参数(表单上传)
         1. 要上传的[二进制数据]
         2. 我这里的imgFile是对应后台表单的名字,别瞎带。
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        [formData appendPartWithFileData:imageData name:@"photo" fileName:fileName mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) 
        if (success) {
            success(response);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
    
}

你可能感兴趣的:(利用AFN以表单的形式上传图片)