简体   繁体   中英

Swift 5 - Upload MultipartFormData Using Alamofire with Image from Gallery

I try to upload image from gallery with several parameter to server but can't find any sample usefull because most of them are deprecated. don't know where to start.

func uploadImageAndData(){

       let periode = periodeField.text
       let kode_wilayah = kodeWilayahField.text
       let nama_petugas = namaPetugasField.text
       let upload_file = myImageView.image

        var parameters = [String:AnyObject]()
        parameters = ["periode":periode,
                      "kode_wilayah":kode_wilayah,
                      "nama_petugas":nama_petugas,
                      "uploaded_file": upload_file] as [String : AnyObject]

        let URL = "myURL"

        Alamofire.upload(
            multipartFormData: { (multipartFormData) in
                if let imageData = upload_file?.jpegData(compressionQuality: 0.3){
                    multipartFormData.append(imageData, withName: self.myFileName)
                }
        }, to:URL)
        { (result) in
            switch result {
            case .success(let upload, _ , _):
                upload.uploadProgress(closure: { (progress) in    
                    //print("uploding")
                    print("Upload Progress: \(progress.fractionCompleted)")
                })  
                upload.responseJSON { response in
                    debugPrint(response)
                    print("done")
                    print(response.result.value)   
                }    
            case .failure(let encodingError):
                print("failed")
                print(encodingError)  
            }
        }
    }

And this in from image picker function and no problem with choosing image from gallery.

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
myImageView.image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
            let data = image.pngData()! as NSData
            data.write(toFile: localPath!, atomically: true)
            let photoURL = URL.init(fileURLWithPath: localPath!) 
        }
        self.dismiss(animated: true, completion: nil)  
    }

I can get the path but can't give it to upload function. I really appreciate for your help.

Try this, i think this will help you.

    func imagupload(){
       let periode = periodeField.text
       let kode_wilayah = kodeWilayahField.text
       let nama_petugas = namaPetugasField.text
       let upload_file = myImageView.image

        var parameters = [String:AnyObject]()
        parameters = ["periode":periode,
                      "kode_wilayah":kode_wilayah,
                      "nama_petugas":nama_petugas,
                      "uploaded_file": upload_file] as [String : AnyObject]

        let URL = "myURL"


                        requestWith(endUrl: URL, imageData: myImageView.image!.jpegData(compressionQuality: 1.0), parameters: parameters, onCompletion: { (json) in
                            print(json)

                        }) { (error) in
                            print(error)

                        }
                    }


      func requestWith(endUrl: String, imagedata: Data?, parameters: [String : String], onCompletion: ((JSON?) -> Void)? = nil, onError: ((Error?) -> Void)? = nil){

        let url = endUrl


        let headers: HTTPHeaders = [

            "Content-type": "multipart/form-data"
        ]

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in parameters {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }

            if let data = imagedata{
                multipartFormData.append(data, withName: "imagename", fileName: "imagename.jpg", mimeType: "image/jpeg")
            }

        }, to:url,headers: headers)
        { (result) in
            switch result{
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    let json : JSON = JSON(response.result.value)
                     print(json)
                    if let err = response.error{
                        onError?(err)

                        return
                    }
                    onCompletion?(json)

                }
            case .failure(let error):
               //print("Error in upload: \(error.localizedDescription)")
                onError?(error)

            }

        }

    }

only used imagupload function in whenever you use like,

self.imagupload()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM