Search code examples
swiftalamofiremultipartform-data

How to make alamofire post request with "form-data" parameters


How to make post request in swift using alamofire with parameters as below(screenshot from postman)image is file-type, title is text-type screen shot from postman

I'm trying sth like this:

let headers = [
        "Content-Type": "application/form-data",
        "X-App-Token": user.token!
    ]
    Alamofire.upload(multipartFormData:{ multipartFormData in
        multipartFormData.append(UIImagePNGRepresentation(imgToSend)!, withName: "image")
        multipartFormData.append(titleToSend.data(using: .utf8)!, withName: "title")},
                     usingThreshold:UInt64.init(),
                     to: url!,
                     method:.post,
                     headers:headers,
                     encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.responseJSON { response in
                                debugPrint(response)
                            }
                        case .failure(let encodingError):
                            print(encodingError)
                        }
    })

but I got error: [BoringSSL] Function boringssl_session_errorlog: line 2868 [boringssl_session_write] SSL_ERROR_SYSCALL(5): operation failed externally to the library

and (this is weird) debugger goes into .success but when I log response there is error from api


Solution

  • Try changing

    multipartFormData.append(UIImagePNGRepresentation(imgToSend)‌​!, withName: "image")

    to

    multipartFormData.append(UIImagePNGRepresentation(imgToSend)‌​!, withName: "image", fileName: "sample.png", mimeType: "image/png")

    If you're getting warning like:

    line 2878 [boringssl_session_write] SSL_ERROR_SYSCALL(5): operation failed externally to the library

    You can simply ignore it. This simply means that an operation on the TLS connection failed because the TLS was closed via the close_notify alert. This sort of thing is not a problem in and of itself.

    You can disable OS logging in Xcode to make them go away. With your project window open, go to Project -> Scheme -> Edit Scheme... and add "OS_ACTIVITY_MODE" to the Environment Variables section and set its value to "disable". When you rerun the app those warnings should now not appear.