0

I am trying to upload some data to my server.I am tring to put my data in file and upload.The request body is multipart/form_data with a single parameter named "filemessage" containing text data which has a content-type of application/json

I am not sure how to handle the application/json as content-type for inner data contained by "filemessage".

I am getting 500 internal server error { "erMessage": "Unknown error", "erCode": "UnknownErCode" }

Here is the code.

func testMultipart()
{
let path = Bundle.main.path(forResource: "testregister", ofType: "txt")

            do {
                let mtext = try String(contentsOfFile: path!)
                let dataA = Data(mtext.utf8)
                guard let url = URL(string: "MY URL") else { return false }
                var request = URLRequest(url: url)
                request.httpMethod = "POST"
                let mKey = "filemessage"
                let mFileName = "testregister"
                let mMimeType = "text/plain"
                let boundary = generateBoundary()

                 request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

                let lineBreak = "\r\n"
                var body = Data()
                body.append("--\(boundary + lineBreak)")
                body.append("Content-Disposition: form-data; name=\"\(mKey)\"; filename=\"\(mFileName)\"\(lineBreak)")
                body.append("Content-Type: \(mMimeType + lineBreak + lineBreak)")
                body.append(dataA)
                body.append(lineBreak)


                request.httpBody = dataA

                let session = URLSession.shared
                session.dataTask(with: request) { (data, response, error) in
                    if let response = response {
                        print(response)
                    }
                    }.resume()

    }
     catch(_){print("error")}

    }


 func generateBoundary() -> String 
 {
   return "Boundary-\(NSUUID().uuidString)"
  }
pythonNinja
  • 453
  • 5
  • 13
  • Did you check the API using PostMan? – Sahil Manchanda Jun 25 '19 at 10:26
  • Yes same error in Postman as well.There I have ensured that i dont enter Content-type .Followed this one here "https://stackoverflow.com/questions/16015548/tool-for-sending-multipart-form-data-request".Only thing is that it runs via curl command – pythonNinja Jun 25 '19 at 11:17

0 Answers0