Swift upload file to PHP server

2019-04-09 06:45发布

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...

1条回答
一纸荒年 Trace。
2楼-- · 2019-04-09 07:33

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

查看更多
登录 后发表回答