Search code examples
swiftimagepdfuploadalamofire

how to upload pdf and image(any one whichever selected) file picked from phone via alamofire in swift


This is the function calling on selecting the file. The parameters needs to be send. And the request url is the server url.

func Upload()
    { 
        var request = URLRequest(url: URL(string: Constants.mainApi + 
        Constants.ADD_CLAIM_DOC)!)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", 
        forHTTPHeaderField: "Content-Type")
        request.setValue("Bearer \(userToken)", forHTTPHeaderField: 
         "Authorization")

        let parameters = ["FileName": myURL as AnyObject,
                              "ClaimID":self.ClaimID!
                ] as [String : Any]
    }

Solution

  • func UploadDoc(){

        let URL1 = URL(string: Constants.mainApi + Constants.ADD_CLAIM_DOC)!
    
        let filename = myURL?.lastPathComponent
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(self.myURL!, withName: filename)
                multipartFormData.append((self.ClaimID?.data(using: .utf8)!)!, withName: "ClaimID")
    
        },
            to: URL1,
            method : .post,
            headers : Constants.headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
    
    
                case .failure(let encodingError):
                    print(encodingError)
    
        })
    
    
    }