gpt4 book ai didi

ios - 使用 Alamofire 从图库上传带有参数和标题的图像

转载 作者:行者123 更新时间:2023-11-28 10:50:07 25 4
gpt4 key购买 nike

我正在尝试上传图片,但还需要传递参数和 header ,从谷歌那里获得了有关参数的帮助,但也不知道如何传递 header 。传递下面的代码,请指导。

下面是我的代码:

if (request.requestType == "Multipart")
{
var strToken : String = ""
if let access_token = UserDefaults.standard.string(forKey: "auth_token"){
let tokenValue = String(format: "Token %@", access_token);
strToken = tokenValue
}

let headers: HTTPHeaders = [
"Authorization": strToken,
"Content-Type": "multipart/form-data"
]

let img = request.image
let imgData = UIImageJPEGRepresentation(img, 0.2)!
do{

let strURL = try strCompleteURL.asURL()
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "image_path",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
},
to:strURL)
{ (result) in
switch result {
case .success(let upload, _, _):

upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})

upload.responseJSON { response in
if response.result.isSuccess {
print(response.result.value as Any)
if let data = response.data{
self.response.responseCode = response.response?.statusCode
self.processResult(data);
}
}
}

case .failure(let encodingError):

print(encodingError)
}
}
}
catch{

}

上面的代码尝试上传图片但由于缺少标题而没有成功,请指导如何传递标题和参数。

谢谢

最佳答案

你好,我用过这样的标题

func uploadImage( image:UIImage, url:String, _ successBlock:@escaping ( _ response: JSON )->Void , errorBlock: @escaping (_ error: NSError) -> Void ){

let path = baseUrl + url
print(path)


let headers = ["authorization": AppData().token]
let imgData = UIImageJPEGRepresentation(image, 0.2)!

let URL = try! URLRequest(url: path, method: .post, headers: headers)


Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgData, withName: "image",fileName: "file.jpg", mimeType: "file")
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, with: URL) { (result) in
switch result {
case .success(let upload, _, _):

upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})

upload.responseJSON { response in
print(response.result.value)
if let value = response.result.value {
let json = JSON(value)
successBlock(json)
}
}

case .failure(let encodingError):
print(encodingError)
errorBlock(encodingError as NSError)

}
}

}

关于ios - 使用 Alamofire 从图库上传带有参数和标题的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46464709/

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