gpt4 book ai didi

ios - 如何使用 Alamofire multipart 在参数中发送数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:28:03 40 4
gpt4 key购买 nike

我正在使用 Alamofire 将图像和文件上传到服务器。但是我在发送带有图像参数的数组时遇到了问题。但是当我在参数中发送一个数组时,它会将数组转换为 JSON 字符串。但我想在参数中发送一个数组,而不是 JSON 字符串。我搜索了很多,但没有找到任何解决方案。所以请告诉我我的代码有什么问题。我正在使用以下代码:

let params = ["id":"112","arrayParam":["1232","12344","14325"]]

let url = www.khxjjhdfsj.com/hsdgs
let headers: HTTPHeaders = [
/* "Authorization": "your_access_token", in case you need authorization header */
"Content-type": "multipart/form-data"
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params
{
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData
{
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "image/png")
}
if let data = pdfData
{
multipartFormData.append(data, withName: "file", fileName: fileName, mimeType:"application/pdf")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
if let err = response.error
{
onError?(err)

return
}



}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
onError?(error)
}
}

最佳答案

您需要将图像参数与其他请求参数一起传递。在下面的代码中像这样传递数组参数:

Alamofire.upload(
multipartFormData: { multipartFormData in
// Pass your image parameter in imgObj
if let imageData = UIImageJPEGRepresentation(imgObj, 1) {
multipartFormData.append(UIImagePNGRepresentation(imgObj)!, withName: "profile_image", fileName: "THDC", mimeType: "image/png")
}
// Send other request parameters
for (key, value) in yourArray {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
},to: YourURL,headers:[:],
encodingCompletion: { encodingResult in

switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
SVProgressHUD.dismiss()
debugPrint("SUCCESS RESPONSE: \(response)")

if let dicObj = response.result.value as? NSDictionary {
print(dicObj)

}
}
case .failure(let encodingError):
SVProgressHUD.dismiss()
print("ERROR RESPONSE: \(encodingError)")
}
}
)

关于ios - 如何使用 Alamofire multipart 在参数中发送数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51360413/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com