![](/img/trans.png)
[英]How to upload an Image from iPhone, using SWIFT, to the Google App Engine blobstore?
[英]Upload Image file from app Swift
我正在嘗試將圖像文件上傳到我的服務器。 下面的屏幕顯示通過郵遞員的呼叫。
在表單數據主體中使用KEY: “ image”和Value: 123.png [image file] 。
我想使用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
格式
編碼
let img = /// this is your image
let encodedString = UIImagePNGRepresentation(img)?.base64EncodedString()
解碼:
let data_from_response = /// from your response
let decodeData = Data(base64Encoded: data_from)
由於您是通過請求正文發送dictionary
,因此您需要將dictionary
轉換為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
旁注避免implicit optional unwrapping
義!
,可以if let
或guard
語句中使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.