【问题标题】:Upload multiple images in Alamofire在 Alamofire 中上传多张图片
【发布时间】:2018-05-31 01:15:04
【问题描述】:

我想使用 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)
                        }
    })
}

【问题讨论】:

  • 完全不相关,而不是HTTPMethod(rawValue: "POST")!,您可以使用.post。减少语法噪音并避免出现简单的印刷错误。

标签: swift alamofire multipartform-data


【解决方案1】:

有两种方法可以发送多个文件。

  1. 您可以为每个文件使用唯一的 name(在这种情况下,name 的值是 image0image1 等):

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

    这导致$_FILES 的:

    $_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";
        };
    };
    

    (忽略此输出的格式,而只关注此嵌套目录结构中的键/值组合:就此输出而言,我让 Web 服务将 $_FILES 作为 JSON 发送回来,然后我让Alamofire 解析它,这就是结果字典在我的客户端应用程序中的输出方式。)

  2. 或者,您可以通过在字段名称后包含[] 来为name 使用数组,例如,字面意思是image[]

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

    这会导致服务器收到以下内容:

    $_FILES =     {
        image =         {
            error =             (
                0,
                0
            );
            name =             (
                "image0.png",
                "image1.png"
            );
            size =             (
                23578,
                338685
            );
            "tmp_name" =             (
                "/tmp/phpI4XrwU",
                "/tmp/php3kVhhl"
            );
            type =             (
                "image/png",
                "image/png"
            );
        };
    };
    

这仅取决于 Web 服务期望创建请求的方式。

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2019-11-24
    • 2017-09-09
    • 2017-03-08
    • 1970-01-01
    • 2016-11-22
    • 2019-11-15
    相关资源
    最近更新 更多