如何使用Alamofire在请求正文中上传图像文件?

时间:2017-03-22 21:11:12

标签: ios http networking upload alamofire

我是iOS开发的新手,现在我正在使用Alamofire编写一个应用程序将图像上传到服务器,但经过几个小时的寻找解决方案和阅读文档后,我仍然没有让它工作。有人可以帮忙吗?谢谢。到目前为止,这是我的代码:

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)")
    }

基于API(我只是前端开发人员),我可以使用请求正文上传图像,并可以保持图像文件不变(不需要编码),但我不确定使用{ {1}}是一个正确的解决方案。此外,当我尝试打印出请求时,我没有看到整个curl命令。

1 个答案:

答案 0 :(得分:1)

尝试从目录

中的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()

}

然后在almofire中使用imageURL:

multipartFormData.appendBodyPart(fileURL: imageURL, name: "ISHC_IMAGE_NAME")