从iOS发送多部分POST请求并在PHP的$_POST
中读取参数,可以使用以下方法:
URLSession
发送多部分POST请求:在iOS中,可以使用URLSession
发送多部分POST请求。以下是一个示例代码:
import Foundation
let url = URL(string: "https://example.com/upload.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let data = "your data".data(using: .utf8)!
var body = Data()
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.jpg\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
body.append(data)
body.append("\r\n".data(using: .utf8)!)
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error!)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
在PHP中,可以使用$_POST
超全局变量来读取POST请求中的参数。以下是一个示例代码:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$file = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
move_uploaded_file($file_tmp, "uploads/$file");
echo "File uploaded successfully.";
} else {
echo "Invalid request method.";
}
?>
在这个示例中,我们使用$_FILES
超全局变量来读取上传的文件信息,然后将文件移动到uploads
目录下。
推荐的腾讯云相关产品:
这些产品可以帮助您快速构建、部署和管理云计算应用,提高应用的可用性、性能和安全性。
领取专属 10元无门槛券
手把手带您无忧上云