如何使用Alamofire上传数组或文件列表(图像)

时间:2018-04-02 08:08:37

标签: swift alamofire multipartform-data

我使用以下代码将图像上传到服务器并且工作正常但我需要针对一个参数上传一个数组或图像列表(即“hunter_pictures”)

Alamofire.upload(multipartFormData: { multipartFormData in  
   multipartFormData.append(UIImageJPEGRepresentation(spottingImage, 1)! , withName: "hunt_pictures", fileName: "user.jpg", mimeType: "image/jpeg")
   multipartFormData.append((userID.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "user_id")
                  },
                             to: url,
                            encodingCompletion: { encodingResult in
                                switch encodingResult {
                                case .success(let upload, _, _):

                                case .failure(let encodingError):
                                    print(encodingError)

                                }
                        })

3 个答案:

答案 0 :(得分:1)

试试这个方法:

func uploadImages(pictures: [UIImage]) {

    let url = "your url"
    let headers: HTTPHeaders = [Keys.authorization: "your token"]

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        for image in pictures {
            if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg")
            }
        }

    }, to: url, method: .post, headers: headers) { (encodingResult) in

        switch encodingResult {

        case .success(let upload, _, _):
            upload.responseJSON { (response) in

                let json = response.result.value
                print(json)
            }

        case .failure(let encodingError):
            print(encodingError.localizedDescription)
        }
    }
}

答案 1 :(得分:1)

@ maxwel的答案只进行了一次修改,只需在fileName“hunter_picture.jpg”中添加文件格式。添加了.jpg并且有效

Alamofire.upload(
    multipartFormData: { multipartFormData in
    multipartFormData.append((userId.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "userID")

       for (index,image) in self.spottingImages.enumerated() {
          if let imageData = UIImageJPEGRepresentation(image, 1) {
            multipartFormData.append(imageData, withName: "hunter_picture[\(index)]", fileName: "hunter_picture.jpg", mimeType: "image/jpeg")  }
                                    }
    },
                to: url,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        print(upload)
                    case .failure(let encodingError):
                        print(encodingError)}
            })

答案 2 :(得分:0)

整合多张图片上传的步骤:

  1. 使用成功和失败关闭将图像数组和参数作为函数参数发送。

  2. 将图片和参数附加到multipartFormData

  3. 在相应的关闭中返回success / failure

  4. 代码段:

    func callAPIForImagesUpload(images: [UIImage],
                                parameters:[String: String]?,
                                success:@escaping ((_ response: Any?) -> Void),
                                failure:@escaping ((_ error: Error?) -> Void)) {
        let apiURL = "xyz/"
        let requestHeaders: HTTPHeaders = ["Authorization": "token value"]
        let fileName = "user" // This will be the parameter name in which server is expecting the image data
    
        Alamofire.upload(multipartFormData: { multipartFormData in
    
            for i in 0..<images.count {
                if let imageData = UIImageJPEGRepresentation(images[i], 1) {
                    multipartFormData.append(imageData, withName: "image_" + "\(i)", fileName: fileName, mimeType: "image/jpeg")
                }
            }
    
            // Append parametrs too, if any
            let params = parameters ?? [String: String]()
            for (key, value) in params {
                // Appending parameters in the request
                multipartFormData.append((value.data(using: .utf8))!, withName: key)
            }
    
        }, to: apiURL, method: .post, headers: requestHeaders) { encodingResult in
    
            switch encodingResult {
            case .success(let upload, _, _):
                // Check whether status code lie between `200-300` range; mostly it would be `200`
                upload.validate(statusCode: 200..<300).responseJSON(completionHandler: { receivedInfo in
                    print("Success: \(receivedInfo.result.value ?? "error occurred in response value")")
                    success(receivedInfo.result.value)
                })
            case .failure(let error):
                print("Error: \(error.localizedDescription)")
                failure(error)
            }
        }
    }