我正在尝试使用 Alamofire 从我的照片库上传:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
return
}
let documentDirectory: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let imageName = "temp"
let imagePath = documentDirectory.appendingPathComponent(imageName)
if let data = UIImageJPEGRepresentation(image, 80) {
do {
try data.write(to: URL(fileURLWithPath: imagePath), options: .atomic)
} catch let error {
print(error)
}
}
Alamofire.upload(.POST, "\(self.app_url)/user/upload", multipartFormData: { formData in
let filePath = NSURL(fileURLWithPath: image)
formData.appendBodyPart(fileURL: filePath, name: "upload")
formData.appendBodyPart(data: "Alamofire".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "test")
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success:
print("SUCCESS")
case .Failure(let error):
print(error)
}
})
self.dismiss(animated: true, completion: nil)
}
它打印:
Ambiguous reference to member 'upload(_:to:method:headers:)'
有人可以解释一下如何解决这个问题吗?
谢谢并问候!
最佳答案
在 Swift 3 和 Alamofire 4 中
这里是如何使用 Alamofire 上传的完整实现
将以下内容添加到您的 ViewController 类中:
UIImagePickerControllerDelegate
和UINavigationControllerDelegate
创建按钮:
首先创建一个按钮并在选择器 View 中实现以下方法
@IBAction func btnSelectProfileImageClicked(_ sender: Any) {
let ImagePicker = UIImagePickerController()
ImagePicker.delegate = self
ImagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(ImagePicker, animated: true, completion: nil)
}
然后实现以下 UIPicker 方法:
func imagePickerController( _ picker: UIImagePickerController,didFinishPickingMediaWithInfo info:[String : Any] ) {Imgprofile.image = info[UIImagePickerControllerOriginalImage] as? UIImage self.dismiss(animated: true, completion: nil)}
制作另一个按钮,使用 Alamofire 将数据传递到 URL,并为其提供一个
@IBAction
导出:
输入以下数据
@IBAction func btnUpdateProfileSelected(_ sender: Any) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.Imgprofile.image!, 1)!, withName: "Prescription", fileName: "Profile_Image.jpeg", mimeType: "image/jpeg")
}, to:" Your URL Here where You want to Upload")
{ (result) in
switch result {
case .success(let upload, _, _):
print(result)
upload.uploadProgress(closure: { (progress) in
print(progress)
})
upload.responseJSON { response in
//print response.result
print(response);
}
case .failure(let encodingError):
print(encodingError);
}
}
}
仅此而已
希望这有帮助
For Full sample code or any doubts please comment. I will provide you the sample code for this. Which Includes the Fetching as well as upload data using Alamofire.
谢谢
关于Swift - Alamofire - 从照片库上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997365/