gpt4 book ai didi

swift - 使用 multipartFormData 上传图像时 Alamofire 请求正文为零

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:54 25 4
gpt4 key购买 nike

我似乎在使用 Alamofire 上传图片和传递参数方面遇到了问题。我有一个非常简单的多部分数据函数,如下所示:

sessionManager.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
print("\(value)")
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "document", mimeType: "image/png")

}, to: baseURL + "/documents", encodingCompletion: { (result) in
switch result{
case .success(let upload, _, _):
upload.validate().responseJSON { response in
print("Succesfully uploaded")

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

}
})

我有 OAuth2Handler,我已经为 header 和授权实现了它,它适用于所有其他请求。我也尝试过直接使用 Alamofire 对象在没有包装器的情况下实现这个,但仍然没有成功。当我检查请求时,我注意到 httpBody 始终为零,这对应于我从服务器收到的错误消息,消息说我没有传递必需的参数。

最佳答案

这对我有用 Swift 4

func callPostApiImage(api:String, parameters:[String:AnyObject]?,image:UIImage,Name:String, mime_type:String = "image/jpg",  complition:@escaping (AnyObject)->Void){

// Encode Data
let base64EncodedString = toBase64EncodedString(toJsonString(parameters: parameters!))

let File_name = "image_" + String(arc4random()) + ".jpg"

Alamofire.upload(multipartFormData: { (multipartFormData) in

multipartFormData.append(UIImageJPEGRepresentation(image, 0.5)!, withName: Name, fileName: File_name, mimeType: mime_type)
multipartFormData.append(base64EncodedString.data(using: String.Encoding.utf8)!, withName: "jsondata")

}, to:api){ (result) in

switch result {

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

upload.uploadProgress(closure: { (progress) in

print(progress)

})

upload.responseJSON { response in

print(response.result)

}

case .failure(let encodingError):

print("",encodingError.localizedDescription)
break
}
}
}

// Base64EncodedString
func toBase64EncodedString(_ jsonString : String) -> String
{
let utf8str = jsonString.data(using: .utf8)

let base64Encoded = utf8str?.base64EncodedString(options: [])

return base64Encoded!
}

关于swift - 使用 multipartFormData 上传图像时 Alamofire 请求正文为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51767225/

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