Anukool
Anukool

Reputation: 812

How to upload PDF file in swift using form-data or any other method

can we upload pdf/doc file using form-data in swift. Or any other way to upload. if possible please provide working example as i am new in this technology.

Upvotes: 1

Views: 6482

Answers (1)

Chetan Daksh
Chetan Daksh

Reputation: 41

Its good to use excellent Alamofire library to upload any doc (such as pdf file).The below code will explain how to use alamofire to upload a file

Alamofire.upload(
        multipartFormData: {
            multipartFormData in

            if let urlString = urlBase2 {
                let pdfData = try! Data(contentsOf: urlString.asURL())
                var data : Data = pdfData

                multipartFormData.append(pdfData, withName: "pdfDocuments", fileName: namePDF, mimeType:"application/pdf")
                for (key, value) in body {
                    multipartFormData.append(((value as? String)?.data(using: .utf8))!, withName: key)
                }

                print("Multi part Content -Type")
                print(multipartFormData.contentType)
                print("Multi part FIN ")
                print("Multi part Content-Length")
                print(multipartFormData.contentLength)
                print("Multi part Content-Boundary")
                print(multipartFormData.boundary)
            }
    },
        to: url,
        method: .post,
        headers: header,
        encodingCompletion: { encodingResult in

            switch encodingResult {

            case .success(let upload, _, _):
                upload.responseJSON { response in
                    print(" responses ")
                    print(response)
                    print("Responses ended")

                    onCompletion(true, "Something went wrong", 200)

                }
            case .failure(let encodingError):
                print(encodingError)
                onCompletion(false, "Something went wrong", 200)
            }
    })

Upvotes: 3

Related Questions