0

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.

enter image description here

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!

Shubham
  • 1,230
  • 2
  • 12
  • 26
  • I'm wondering : I see a space after `name=`: `name= msgRequest` and `name= \"\(imageName)\"`, and also in `filename`. Is `msgRequest` correct JSON? – Larme Jan 12 '23 at 18:39
  • @Larme Fixed the extra space issue but still got the same response. and for msgRequest, I am using the codable protocol to encode the model. so I hope it's correct. – Shubham Jan 12 '23 at 19:02
  • 400 error code means that something wrong with your request. Try to add breakpoint before `session.dataTask(with: urlRequest)` and check status of your `urlRequest`. Looks like some value in it is wrong or absent. For example you can add `print(urlRequest)` – Володимир Ukraine Jan 12 '23 at 21:44
  • @ВолодимирUkraine I have added the urlRequest data above. – Shubham Jan 13 '23 at 07:08
  • @Shubham in the screen from postman there are 8 headers. You request does not contain all of them. That's why I asked to print and check `urlRequest` instead of `urlRequest.data`. Or you can duplicate you request in postmen and delete unnecessary headers and test it again. But right now you urlRequest do not equal your request in postman, that's the reason. – Володимир Ukraine Jan 13 '23 at 08:53
  • @ВолодимирUkraine I have updated the request headers above. After removing unnecessary headers from postman all other headers I am already sending in the request headers. – Shubham Jan 13 '23 at 10:15

0 Answers0