gpt4 book ai didi

ios - 从 Swift 应用程序上传图像文件

转载 作者:行者123 更新时间:2023-11-30 12:04:10 26 4
gpt4 key购买 nike

我正在尝试将图像文件上传到我的服务器。下面的屏幕显示了通过 postman 的调用。

使用KEY:“图像”值:123.png [图像文件]形式-数据正文。

enter image description here

我想使用 swift 在我的应用程序中实现相同的功能。我尝试了不同的解决方案,但没有找到合适的解决方案。

我正在 UIImagePicker 的帮助下选择图像:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 
{
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
uploadImage(image: image!, url: "profile_image/")
}

我调用uploadImage函数来上传图片。

func uploadImage(image: UIImage, url: String) {
let urlString = "http://example.com/path/"+url
guard let url = URL(string: urlString) else { return }
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let token = UserDefaults.standard.object(forKey: "token") as? String
request.addValue("Token "+token!, forHTTPHeaderField: "Authorization")
let imageData = UIImagePNGRepresentation(image)!.base64EncodedData()
//let postString = "image=\(imageData))"
//request.httpBody = postString.data(using: .utf8)

let imgDict = ["image": imageData]

do {
let jsonBody = try JSONEncoder().encode(imgDict)
print(jsonBody)
request.httpBody = jsonBody
} catch let jsonError {
print(" Parsing Error: "+jsonError.localizedDescription)
}

URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
if error != nil {
print("Image upload API Error: "+error!.localizedDescription)
}
guard let data = data else { return }
do {
print(data)
let responseData = try JSONDecoder().decode(BasicResponseParameter.self, from: data)
print(responseData)

if responseData.success {
print("Image uploaded")
}
else {
print("Image upload API Failed : "+responseData.message!)
DispatchQueue.main.async(execute: {
popAlert(title: "FAILED", message: responseData.message!, owner:self)
})
}
} catch let jsonError {
print("Image upload API JSON Error :"+jsonError.localizedDescription)
}
}.resume()
}

感谢任何帮助。

最佳答案

我建议您将图像编码(将图像发送到服务器时)和解码(查询图像返回时)为 base64 格式

To encode

let img = /// this is your image 
let encodedString = UIImagePNGRepresentation(img)?.base64EncodedString()

To Decode:

let data_from_response = /// from your response 
let decodeData = Data(base64Encoded: data_from)

由于您要通过请求正文发送字典,因此您需要将字典转换为json

guard let imgDataString = String.init(data: encodedString, encoding: String.Encoding.utf8) else { return } 

let imgDict = ["image": imgDataString ]

let jsonData = try! JSONSerialization.data(withJSONObject: imgDict, options: .prettyPrinted)

request.httpBody = jsonData

旁注避免隐式可选展开意味着!,可以使用if letguard 语句

关于ios - 从 Swift 应用程序上传图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859282/

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