使用Alamofire上传多张图片

4

我想使用Alamofire上传多个图片到服务器。

所有工作都很好,但是只有一个图片被上传。我需要上传多个或更多的图片,具体取决于登录用户。我正在使用一个名为DKImagePickerController的库从图库或相机中选择图片。

func upload() {

    //shortcuts
    let id = userr.integer(forKey: "id")
    let plateId = plateIdTextField.text!
    let customerName = customerNameTextField.text!
    let customerContact = customerContactTextField.text!
    let package = radioButtonsController.selectedIndex + 1

    var parameters: [String: Any]
    parameters = ["user_id": id,
                  "package": package,
                  "plate_id": plateId,
                  "customer_name": customerName,
                  "customer_contact": customerContact]

    let spinningActivity = MBProgressHUD.showAdded(to: self.view, animated: true)
    spinningActivity?.labelText = "uploading.."
    spinningActivity?.detailsLabelText = "Please wait"

    Alamofire.upload(multipartFormData: { multipartFormData in

        for fileImage in self.fileUIImage {
            multipartFormData.append(UIImagePNGRepresentation(fileImage)!, withName: "image", fileName:"image.png", mimeType: "image/png")
        }

        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }
    },
                     to: uploadURL,
                     method: HTTPMethod(rawValue: "POST")!,
                     encodingCompletion: { encodingResult in
                        switch encodingResult {

                        case .success(let upload, _, _):

                            upload.responseJSON { response in

                                //Unpacking
                                guard let result = response.result.value else { return }
                                spinningActivity!.hide(true)
                                print("\(result)")
                                self.BackToHomePage()
                            }
                        case .failure(let encodingError):
                            print(encodingError)
                        }
    })
}

1
完全没有关系,你可以使用.post代替HTTPMethod(rawValue: "POST")!。这样可以减少语法噪音并避免简单的排版错误。 - Rob
1个回答

4
有两种方法可以发送多个文件。
  1. You can use a unique name for each file (in this case, name values of image0, image1, etc.):

    for (index, image) in images.enumerated() {
        multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image\(index)", fileName: "image\(index).png", mimeType: "image/png")
    }
    

    That results in a $_FILES of:

    $_FILES =     {
        image0 =         {
            error = 0;
            name = "image0.png";
            size = 23578;
            "tmp_name" = "/tmp/php1bc19G";
            type = "image/png";
        };
        image1 =         {
            error = 0;
            name = "image1.png";
            size = 338685;
            "tmp_name" = "/tmp/phpcGS5d6";
            type = "image/png";
        };
    };
    

    (Ignore the format of this output, but rather just focus on the key/value combinations in this nested directory structure: In terms of what this output is, I had web service send $_FILES back as JSON, I then let Alamofire parse it, and this is how the resulting dictionary was output in my client app.)

  2. Alternatively, you can use an array for the name by including a [] after the field name, e.g., literally image[]:

    for (index, image) in images.enumerated() {
        multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image[]", fileName: "image\(index).png", mimeType: "image/png")
    }
    

    That results in the following to be received on the server:

    $_FILES =     {
        image =         {
            error =             (
                0,
                0
            );
            name =             (
                "image0.png",
                "image1.png"
            );
            size =             (
                23578,
                338685
            );
            "tmp_name" =             (
                "/tmp/phpI4XrwU",
                "/tmp/php3kVhhl"
            );
            type =             (
                "image/png",
                "image/png"
            );
        };
    };
    
这只取决于网络服务期望请求的创建方式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接