我想使用 URLSession 类的 uploadTask 方法将图像发送到服务器,我有以下上传图像的功能,但我无法读取 php 文件中的任何内容。
@IBAction func uploadImage(_ sender: Any) {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let url = URL(string: "http://www.localhost.com/destiny.php")!
let file: URL = Bundle.main.url(forResource: "colors", withExtension:"jpg")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")
let task = session.uploadTask(with: request, fromFile: file) {
(data: Data?, res: URLResponse?, error: Error?) in
defer {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
if error != nil {
print(error!.localizedDescription)
return
}
if data != nil{
let strData = String(data:data!, encoding:String.Encoding.utf8)
print(strData!)
}
let code = (res as! HTTPURLResponse).statusCode
print(code)
if code != 201 {
print(HTTPURLResponse.localizedString(forStatusCode: code))
return
}
print("Uploaded!")
}
task.resume()
}
php 文件包含以下代码:
print_r($_POST)
print_r($_FILES)
我的输出应用程序:
Array()
Array()
200
no error
我希望你能帮助我找出问题所在。
问候。