iOS multipart/form-data表单上传图片到服务器

NSString *ext = @"";
    if (UIImagePNGRepresentation(image)) {//返回为png图像。
        ext = @"png";
    }else {//返回为JPEG图像。
        ext = @"jpeg";
    }
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:self.uploadAliInfo.Key forKey:@"Key"];
    [parameters setValue:self.uploadAliInfo.OSSAccessKeyId forKey:@"OSSAccessKeyId"];
    [parameters setValue:self.uploadAliInfo.Policy forKey:@"Policy"];
    [parameters setValue:self.uploadAliInfo.Signature forKey:@"Signature"];
    [parameters setValue:self.uploadAliInfo.Success_action_status forKey:@"Success_action_status"];
    [parameters setValue:[NSString stringWithFormat:@"temp.%@", ext] forKey:@"file"];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"application/xml", nil];
   NSURLSessionDataTask *uploadTask = [session POST:[NSString stringWithFormat:@"http:%@", self.uploadAliInfo.Url] parameters:parameters constructingBodyWithBlock:^(id  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData :imageData name:@"temp" fileName:[NSString stringWithFormat:@"temp.%@", ext] mimeType:@"multipart/form-data"];
   } progress:^(NSProgress * _Nonnull uploadProgress) {
       
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
   }];

你可能感兴趣的:(iOS multipart/form-data表单上传图片到服务器)