Home > OS >  Upload an .XML file with a name via POST method in SWIFT
Upload an .XML file with a name via POST method in SWIFT

Time:02-22

As part of an HTTP server request I need to upload an .XML file in a POST request that includes query information. Yet simply using URLSession.shared.uploadTask(with:, fromFile:) doesn't seem to work. Like the following:

func reportRequest(url: URL) -> Void {
    let fileURL: URL = URL(fileURLWithPath: ".../search_xml.xml")
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "POST"
    urlRequest.setValue(authToken, forHTTPHeaderField: "authorization")
    let task = URLSession.shared.uploadTask(with: urlRequest, fromFile: fileURL) {data, response, error in
        print(String(data: data!, encoding: .utf8)!)
        print(response)
    }
    task.resume()

I have achieved this on Python using the files parameters in the requests module, and passing a dictionary in it like the following:

headers = {'authorization': authToken, }
files = {'xmlRequest': open('.../search.xml', 'rb')}
response = requests.post(url, headers=headers, files=files)

I also achieved this in RestMan (a browser extension to manage REST APIs) by adding a form data in the body, with "xmlRequest" as key and choosing the .XML file as value.

It might seem like I have to build request body myself in SWIFT, but I have little knowledge in that, and the tutorials I find about it are mostly about uploading Images, which might be different.

Thanks in advance!

CodePudding user response:

Here's a generic example to upload a file.

let headers = [
  "content-type": "multipart/form-data;",
  "authorization": "authToken",
]

let parameters = [
  [
    "name": "xmlfile",
    "fileName": "search_xml.xml"
  ]
]

var body = ""
var error: NSError? = nil
for param in parameters {
  let paramName = param["name"]!
  body  = "--\(boundary)\r\n"
  body  = "Content-Disposition:form-data; name=\"\(paramName)\""
  if let filename = param["fileName"] {
    let contentType = param["content-type"]!
    let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
    if (error != nil) {
      print(error)
    }
    body  = "; filename=\"\(filename)\"\r\n"
    body  = "Content-Type: \(contentType)\r\n\r\n"
    body  = fileContent
  } else if let paramValue = param["value"] {
    body  = "\r\n\r\n\(paramValue)"
  }
}

let request = NSMutableURLRequest(url: NSURL(string: "https://example.com/fileupload")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
  • Related