Swift上传文件到PHP服务器 [英] Swift upload file to PHP server
本文介绍了Swift上传文件到PHP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ _ FILES
。这只是一个空的数组。 我明显在Swift方面做错了,这是我的代码:
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,
request.setValue(Keep-Alive,forHTTPHeaderField:Connection)
self.uploadFiles(request,data:data)
} $ b $ forHTTPHeaderField:Content-Type b
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()
}
我很确定我错过了一些东西,我只是无法弄清楚它是什么...
解决方案
POST方法,您需要添加标题应用程序/ x-www-form-urlencoded
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...
解决方案
POST method ,you need add header application/x-www-form-urlencoded
这篇关于Swift上传文件到PHP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文