我想在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只需将密钥在密钥字典中传递 –