简体   繁体   English

使用Content-Type制作Alamofire请求:multipart / form-data

[英]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 我想用Alamofire发出post请求,使用Content-Type: multipart/form-data接受请求并接受有效负载文件我尝试发出请求,你可以从代码中看到但是我得到500个错误代码,我确实做了邮递员中的相同请求和它的工作, 请注意在提出请求后我不希望回复它将是空的

  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. 看看它是否有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM