[英]How to upload image file in the request body with Alamofire?
I'm new to iOS development, and right now I'm writing an app using Alamofire to upload image to server, but after hours of looking for solutions and reading documentation, I still have not made it work yet. 我是iOS开发的新手,现在我正在编写一个使用Alamofire将图像上传到服务器的应用程序,但是在寻找解决方案和阅读文档数小时之后,我仍然没有使其工作。 Can someone please help? 有人可以帮忙吗? Thanks. 谢谢。 This is my code so far: 到目前为止,这是我的代码:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imagePicker.dismiss(animated: true, completion: nil)
//Upload image from here
//Get user for header info
var user = User.getUserInstance()
//Get current patient for header info
var currentPatient = CurrentPatient.getCurrentPatientInstance()
//Server address
let serverAddress = user.serverAddress
//Prep for headers
var headers = [
"ISHC_LOGIN": user.username,
"ISHC_PWD": user.password,
"ISHC_API_TOKEN":"token",
"ISHC_OPERATION":"CreateImage",
"ISHC_IMAGE_NAME":"test",
"ISHC_EXTAPP_ID":"app",
"ISHC_FOLDER_ID":currentPatient.getCurrentPatient().patientID,
"ISHC_EXTAPP_VALUE":"IS_WEB_STAGE",
"Accept-Encoding": "application/xml"
]
print("UPLOADING...")
let request = Alamofire.upload(multipartFormData: { multipartFormData in
let imageData = UIImagePNGRepresentation(image)
multipartFormData.append(imageData!, withName: "image", fileName: "file.png", mimeType: "image/png")
// multipartFormData.append((value.data(using: .utf8))!, withName: key)
}, to: serverAddress, method: .post, headers: headers,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
debugPrint("RESPONSE IS:\(response)")
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
debugPrint("request is:\(request)")
}
Based on the API (I'm only the front-end dev), I can upload the image using the request body and can keep the image file as is (no encoding required), but I'm not sure using multipartFormData.append
is a correct solution. 基于API(我只是前端开发人员),我可以使用请求正文上传图像,并且可以按原样保留图像文件(无需编码),但是我不确定使用multipartFormData.append
是否正确的解决方案。 Also, when I try to print out the request, I did not see the whole curl command. 另外,当我尝试打印请求时,没有看到整个curl命令。
Try to save the selected image from UIImagePickerController in Directory 尝试将UIImagePickerController中的选定图像保存在目录中
func saveUserProfileAtDirectory (userImage : UIImage) -> NSURL {
let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// create a name for your image
let imageURL = documentsDirectoryURL.URLByAppendingPathComponent("pic.jpg")
if NSFileManager.defaultManager().fileExistsAtPath(imageURL.path!) {
do {
try NSFileManager.defaultManager().removeItemAtPath(imageURL.path!)
}
catch
{
}
}
if UIImageJPEGRepresentation(userImage, 1.0)!.writeToFile(imageURL.path!, atomically: true) {
return imageURL
} else {
print("error saving file")
}
return NSURL()
}
Then use imageURL in almofire: 然后在almofire中使用imageURL:
multipartFormData.appendBodyPart(fileURL: imageURL, name: "ISHC_IMAGE_NAME")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.