如何在Swift 3 iOS中将服务器中的图像与其他参数一起上传

时间:2017-03-20 05:52:05

标签: ios iphone swift3 afhttprequestoperation

##这是我的Objective-c代码,我将图像发送到服务器。

    NSString *str=@"https://user.co/users/";
    NSString *urlString=[[NSString stringWithFormat:@"%@",str] stringByAppendingString:@"add"];
    AFHTTPSessionManager *manager1 = [AFHTTPSessionManager manager];
    manager1.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    [manager1 POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
         [formData appendPartWithFileData:pictureData name:@"profile_pic" fileName:@".jpg" mimeType:@"image/jpg"];
    }

          progress:nil success:^(NSURLSessionDataTask *task, id responseObject){
              NSLog(@"Response is success : %@", responseObject);
              if ([[responseObject valueForKey:@"sucess"]isEqualToString:@"0"]) {
              }else{
              }
          }
           failure:^(NSURLSessionDataTask *task, NSError *error) {
               NSLog(@"Error: %@", error);
           }];

如何在服务器中实现此上传图像以及Swift 3中的其他参数

1 个答案:

答案 0 :(得分:0)

尝试使用almofire多部分数据

Alamofire.upload(multipartFormData: { (multipartFormData) in


        for (key, value) in params{

            if key == "profile_pic"{

                let uploadImage = value as! UIImage

                let imageData = UIImagePNGRepresentation(uploadImage)!
                formData.appendPartWithFileData(imageData , name: "uploaded_file[]", fileName: "uploadImage\(index)x.png", mimeType: "image/png")



                multipartFormData.append(imageData, withName: "uploadImage", fileName: "uploadImage", mimeType: "image/png")

            }else{

                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, with: URL2, encodingCompletion: { (result) in

            switch result {
            case .success(let upload, _, _):

                upload.responseJSON { response in
                    self.delegate?.showSuccessAlert()
                    print(response.request)  // original URL request
                    print(response.response) // URL response
                    print(response.data)     // server data
                    print(response.result)   // result of response serialization
                    //                        self.showSuccesAlert()
                    self.removeImage("frame", fileExtension: "txt")
                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")
                    }
                }

            case .failure(let encodingError):
                self.delegate?.showFailAlert()
                print(encodingError)
            }

        }

    })