title: Upload Pdf, Docx and image file to server using Swift 4
body: <p>I am new to swift, I have been trying to upload pdf, docx and image file from local storage of a Iphone. I have written a code but it doesn't work and I keep getting <strong><em>Status Code: 415</em></strong> from the response. Here is my code:</p>
  
  <pre><code>func uploadfileToServer(completed: @escaping () -&gt; ()){
  
      let theTitle = labelTitle.text
  
  
      guard let url = URL(string: "http://www.--------.com/assignment/post") else {return}
      var request = URLRequest.init(url: url)
      request.httpMethod = "POST"
  
      request.addValue("cf7ab8c9d4efae82b575eabd6bec76cbb86c6108391e036387f3dd5356a582171519367747000", forHTTPHeaderField: "api_key")
  
  
  
  
      let boundary = generateBoundaryString()
  
  
      // Set Content-Type in HTTP header.
      let boundaryConstant = boundary // This should be auto-generated.
      let contentType = "multipart/form-data; boundary=" + boundaryConstant
  
      let directory = NSTemporaryDirectory()
      let fileName = NSUUID().uuidString
  
      // This returns a URL? even though it is an NSURL class method
      let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])
  
  
  
      let fileNamee = fullURL?.path
      let mimeType = "text/csv"
      let fieldName = "uploadFile"
  
      request.setValue(contentType, forHTTPHeaderField: "Content-Type")
  
  
  
      var dataString = "--\(boundaryConstant)\r\n"
  
  
      dataString += "\r\n"
      dataString += "--\(boundaryConstant)--\r\n"
  
      var theBody = Data()
  
  
  
      let sectionID : String?
      sectionID = nil
      let str = "user_id=\(savedsesuid!)" + "&amp;school_id=" + SCHOOL_ID + "&amp;class_id=" + classID + "&amp;section_id=\(sectionID)" + "&amp;subject_id=\(id)"
  
  
  
      if let b = str.data(using: .utf8) {
          theBody.append(b)
      }
  
      let str1 = "&amp;atitle=" + theTitle! + "&amp;class_id=" + classID
  
      if let c = str1.data(using: .utf8){
          theBody.append(c)
      }
  
  
      let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
      var filePath = documentDirectory.appendingFormat("/")
      filePath     = filePath.appendingFormat("/Users/prashanna/Desktop/ebusiness_topic_1_handout.pdf")
      let pdfData  = NSData(contentsOfFile: filePath)
  
      let file = "&amp;afile=" + "\(pdfData)"
  
      if let d = file.data(using: .utf8){
          theBody.append(d)
      }
  
      print(theBody)
  
  
  
      request.httpBody = theBody
  
      URLSession.shared.dataTask(with: request) { (data, response, error) in
          print(response)
          if let httpResponse = response as? HTTPURLResponse {
              let statuscode = httpResponse.statusCode
              if statuscode == 401{
                  self.displayMessage(userMessage: "Sending Failed")
  
  
              }else if statuscode == 200{
                  if error == nil{
                      do{
                          self.displayMessage(userMessage: "File Successfully Uploaded!")
                          DispatchQueue.main.async {
                              completed()
  
                          }
  
                      }
  
                  }
              }
          }
      }.resume()
  
  
  
  }
  
  func generateBoundaryString() -&gt; String {
      return "Boundary-\(NSUUID().uuidString)"
  }
  </code></pre>
  
  <p>Some solutions tell me to convert the file into Data and then send it to server while some say to directly add the file path to your body.
  Need Help!</p>