0
我想將圖像文件上傳到我的服務器。屏幕下方顯示通過郵遞員打電話。從應用程序上傳圖像文件Swift
隨着KEY:「圖像」和值:英揚留學[圖像文件]在形狀數據本體。
我想用迅速來實現我的應用程序相同。我嘗試了不同的解決方案,但力求找到合適的解決方案
我的選擇圖像與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()
}
任何幫助表示讚賞。
謝謝你非常多的答覆拉馬爾:),我用.base64EncodedData()編碼圖像,我得到「數據無法讀取,因爲它不是正確的格式。」錯誤 –
拉馬爾,我擔心我是否正確發送KEY&VALUE。正確的格式/方式/方式是關鍵和價值嗎? @Lamar –
你是否正確地打開了你的圖像? – Lamar