AFNetworking上传图片

基本代码如下

[manager POST:@"" parameters:nil constructingBodyWithBlock:^(id  _Nonnull formData) {
        
        UIImage *image =[UIImage imageNamed:@"image"];
        //png和jpeg的压缩
        NSData *data = UIImagePNGRepresentation(image);
//        NSData *data = 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. name:指服务器获取该图片所用的“键”的名字
         2. fileName:文件在服务器上保存的名字
         */
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"当前进度:%lf / 总进度:%lf",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure");
    }];

你可能感兴趣的:(AFNetworking上传图片)