简体   繁体   中英

making Alamofire Request with Content-Type: multipart/form-data

I want to make post request with Alamofire that take requests with Content-Type: multipart/form-data and accepts payload file I try to make the request as you can see from the code blow but I am getting 500 error code , I did make the same request in Postman and it work , Note after making the request I dont expected response back it will be empty

  let body: [String:String] = [
                "id":"101",
                "message":test,
                "type":"test"
            ]

            let payload = [
                "payload":body
            ]

            let headers = [ "Content-Type" : "multipart/form-data"] 
            Alamofire.request("URL", method: .post, parameters:payload, encoding: JSONEncoding.default, headers: headers).responseObject { (response: DataResponse<ObjectEntity>) in
                guard (response.response?.statusCode == 200 || response.response?.statusCode == 204) else {
                    if response.response != nil {
                        self.showAPILogs(fullURL: self.getFullURL(methodName: methodName), response: response.response, statusCode: response.response!.statusCode)

                    }
                    return
                }
                self.showAPILogs(fullURL: self.getFullURL(methodName: methodName), response: response.response, statusCode: response.response!.statusCode)


            }

Try

let body: [String: String] = [
        "id": "101",
        "message": test,
        "type": "test"
    ]
    Alamofire.upload(multipartFormData: { MultipartFormData in
        for (key, value) in body {
            MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    }, usingThreshold: UInt64.init(),
       to: "URL",
       method: .post,
       headers: ["Authorization": "Your access token"], // As per the web service requirement
       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in

            }
        case .failure(let error):
            print(error)
        }
    })

and see if it works.

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