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

问题描述 投票:0回答:3

我正在使用以下代码将图像上传到服务器,它工作正常,但我需要根据一个参数(即“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)

                                }
                        })
swift alamofire multipartform-data
3个回答
3
投票

@maxwel 的答案只做了一项修改,只需在文件名“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)}
            })

3
投票

试试这个方法:

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)
        }
    }
}

0
投票

整合多图上传步骤:

  1. 将图像数组和参数作为函数参数发送,并带有成功和失败闭包。

  2. 将图像和参数附加到

    multipartFormData

  3. 在相应的闭包中返回

    success
    /
    failure

代码片段:

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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.