conchimnon conchimnon -4 years ago 167
HTTP Question

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. 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. Also, when I try to print out the request, I did not see the whole curl command.

Answer Source

Try to save the selected image from UIImagePickerController in Directory

    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:

multipartFormData.appendBodyPart(fileURL: imageURL, name: "ISHC_IMAGE_NAME")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download