I need to send an image and json data to the server by using multipart/form-data
request by using URLSession. Please refer the below screenshot for request.
I can successfully able to upload the image and json data by using postman. But i am struggling to upload the image and json data by using URLSession
Please refer to the below code
let session = URLSession.shared
let boundary = UUID().uuidString
var urlRequest = URLRequest(url: URL(string: "https://dev.example.com/api/msg/sendmsg")!)
urlRequest.httpMethod = "POST"
urlRequest.setValue(authToken, forHTTPHeaderField: Key.RequestParam.authToken)
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
let imageName = "file"
data.append("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(imageName)\" \r\n".data(using: .utf8)!)
data.append("Content-Type: image/jpeg \r\n".data(using: .utf8)!)
data.append(imageData)
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=msgRequest \r\n".data(using: .utf8)!)
data.append("Content-Type: application/json \r\n".data(using: .utf8)!)
data.append(msgRequest)
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
urlRequest.httpBody = data
session.dataTask(with: urlRequest) { responseData, response, error in
if(error != nil){
print("\(error!.localizedDescription)")
}
guard let responseData = responseData else {
print("no response data")
return
}
if let responseString = String(data: responseData, encoding: .utf8) {
print("uploaded to: \(responseString)")
}
}.resume()
Request headers
["Authorization": "Bearer edasdasddaUzI1NiJ9.eyJqdaaddjY0OCIsImRldmljZUlkIjoiNEI4OTEzREYtQTQyQSEJBmlkcuwWF0IjoxNjcyNzM5NzY1LCasdadadasjk1NjV9.eaddLFCRK0mMICuFhhujhdoaise3M-RiydXoiuhowbfs", "Content-Length": "11314616", "Content-Type": "multipart/form-data; boundary=08D6DB1A-C888-40E5-8BD6-FE218E892A06"]
Below is the urlRequest data
--08D6DB1A-C888-40E5-8BD6-FE218E892A06
Content-Disposition: form-data; name="file"; filename="file1"
Content-Type: "image/jpeg"
ImageData
--08D6DB1A-C888-40E5-8BD6-FE218E892A06
Content-Disposition: form-data; name="msgRequest"
Content-Type: "application/json"
{"msgBody":"Hi there”,”clientId”:”29385422222”}
--08D6DB1A-C888-40E5-8BD6-FE218E892A06--
I am getting the response Status Code: 400
Please help me out with this problem. Thanks!