5

So I'm uploading a file from swift to a PHP server, the POST request arrives as expected with headers and all but I'm unable to get anything out of $_FILES. It's just an empty array.

I'm clearly doing something wrong on the Swift side, this is my code:

func testUpload(){
    let bundle = NSBundle.mainBundle()
    let path = bundle.pathForResource("someTestFile", ofType: "zip")!
    var data: NSData = NSData(contentsOfFile: path)!

    var request = NSMutableURLRequest(URL: NSURL(string: "http://testsite.com/upload")!)
    request.HTTPMethod = "POST"

    let boundary = "----------ds2Gry67efddagdfsfhsHF"
    let contentType = "multipart/form-data; boundary=\(boundary)"
    request.setValue(contentType, forHTTPHeaderField:"Content-Type")
    request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
    self.uploadFiles(request, data: data)
}

func uploadFiles(request: NSURLRequest, data: NSData) {
    var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
    var task = session.uploadTaskWithRequest(request, fromData: data)
    task.resume()
}

I'm pretty sure I'm missing something, I just can't figure out what it is...

matt
  • 2,312
  • 5
  • 34
  • 57
  • Maybe something to do with contentDisposition? – matt Apr 20 '15 at 14:25
  • have you consider using Alamofire instead? – Victor Sigler Apr 20 '15 at 14:54
  • see this very good answer http://stackoverflow.com/questions/26162616/upload-image-with-parameters-in-swift – Victor Sigler Apr 20 '15 at 14:57
  • What type of file are you sending? Are you trying to send anything else with the file? Have you attempted a var_dump of the $_FILE and $_POST arrays? – Jeffrey Apr 21 '15 at 03:31
  • @jkaufman It's just a zip file, and not sending anything else apart from some headers, so $_POST is also empty – matt Apr 21 '15 at 07:31
  • First, to ensure that the Swift code truly is the issue, use [Postman](https://www.getpostman.com) to test your PHP script. Simply attempt to send a .zip file to your page and make sure you receive no errors. – Jeffrey Apr 23 '15 at 00:08

1 Answers1

-1

POST method ,you need add header application/x-www-form-urlencoded