Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire.upload with query parameters

Tags:

alamofire

I'm using Alamofire.upload to upload an image as a .POST multipart to my server. But my server always gets parameters only as a query string, and use multipart only for a file data. So in my request I also need to put some parameters to URL, but it seems Alamofire.upload have't a variant with parameters argument.

Alamofire.upload(
    .POST,
    "https://httpbin.org/post?user=\(userId)&photo=\(photoTitle)",
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
    },
    encodingCompletion: nil
)

For now I just put all parameters by myself directly forming request-string: "https://httpbin.org/post?user=\(userId)&photo=\(photoTitle)". Is there a better way to pass query parameters to Alamofire.upload?

like image 960
user3537411 Avatar asked Dec 14 '25 19:12

user3537411


1 Answers

What can do things better is Alamofire.ParameterEncoding, but it will need some workaround with requests.

    var req: NSMutableURLRequest?
    (req!, _) = Alamofire.ParameterEncoding.URL.encode(
        NSURLRequest(URL: NSURL(string: "https://httpbin.org")!),
        parameters: ["user": userId, "photo": photoTitle]
    )

    Alamofire.upload(
        .POST,
        req!.URLString,
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
        },
        encodingCompletion: nil
    )
like image 52
user3537411 Avatar answered Dec 19 '25 05:12

user3537411



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!