我想在API調用中從圖庫向服務器發送圖像。該圖像必須作爲參數傳遞。要通過圖像作爲參數,我試圖讓圖像的URL像這樣,但它並沒有給予正確的URL ..使用Alamofire無法正常工作將圖像上傳到服務器
var selectedImage : UIImage = image
let imageData: NSData = UIImagePNGRepresentation(selectedImage)! as NSData
let imageStr = imageData.base64EncodedString(options:.endLineWithCarriageReturn)
imageArray.append(image)
而且我試着上傳的圖片是這樣的...
for img in imageArray {
let url = "http://myApp..com/a/images_upload"
let headers = [ "Content-Type":"application/x-www-form-urlencoded"]
let URL = try! URLRequest(url: url, method: .post, headers: headers)
let parameters =
[
"access_token": accessToken
"image": img
] as [String : Any]
let imgData = UIImageJPEGRepresentation(img, 0.2)!
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imgData, withName: "image",fileName: "file.jpg", mimeType: "file")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).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 {
print("IMG UPLOADED!!!")
}
}
case .failure(let encodingError):
print(「ERROR」)
}}}
但是這也是崩潰。我一直有這個問題相當長一段時間了......無法弄清楚確切的解決方案是什麼......希望有人可以幫助... :)也做過很多類似的問題。但沒找到,直到一個解決方案...
編輯:我的參數是:
let Parameters =
[
"access_token": commonVarForAccessToken,
"seller_id": idForNewOldUser,
"product_id": self.productId,
"is_default": "1",
"sequence": 1,
"image": self.localPath
] as [String : Any]
https://stackoverflow.com/questions/39631823/swift-3-alamofilre-4-0-multipart-image-upload-with-progress和https://stackoverflow.com/questions/39809867/alamofire-4-upload-with-parameters – iPatel
確實經歷過之前,@iPatel ...但它沒有幫助... –
使用我的答案https:/ /stackoverflow.com/questions/45651187/upload-photo-file-with-json-and-custom-headers-via-swift-3-and-alamofire-4-i/46116478#46116478只需將密鑰在密鑰字典中傳遞 –