我有一個 iOS 應用程式,它應該通過 POST 請求將影像資料上傳到我在 Nginx 上的 php 服務器。我可以上傳資料,但是當我下載后,上傳的檔案已損壞且較小,我無法打開它。
我已將 post_max_size、max_input_vars 和 upload_max_filesize 的值更改得足夠高,并正確設定了所有權限。
這是我的代碼:
應用程式:
DispatchQueue.global().async {
let url = "url to upload.php"
var urlComponents = URLComponents(string: url!)
urlComponents.queryItems = [
URLQueryItem(name: "filetype", value: "img")
]
var request = URLRequest(url: urlComponents.url!)
request.httpMethod = "POST"
let boundary = UUID().uuidString
let contentType = "multipart/form-data; boundary=\(boundary)"
var body = Data()
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"username\"\r\n\r\n".data(using: .utf8)!)
body.append("\(username)\r\n".data(using: .utf8)!)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"image-upload\"; filename=\"img.jpg\"".data(using: .utf8)!)
body.append("Content-Type: image/jpeg".data(using: .utf8)!)
body.append(imageData) // 2735963 bytes
body.append("\r\n--\(boundary)--".data(using: .utf8)!)
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
let responseString = String(data: data!, encoding: .utf8)
print(responseString!) // final data stored on server: 2734537 bytes
}
task.resume()
}
PHP:
<?php
$user = $_POST['username'];///I need this for the path
$username = str_replace(array("\r", "\n", "'"), '', $user);
$type = $_GET['filetype'];
if ($type == "img")
{
$path = "path to save img.jpg";
$image = $_FILES['image-upload']['tmp_name'];
if (move_uploaded_file($image, $path)) {
echo "Success";
}
else
{
echo "Failed";
}
}
?>
有什么問題嗎?
uj5u.com熱心網友回復:
你錯過了\r\n\r\nafter Content-Type: image/jpeg。
例如:
body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
您可能在最終邊界之后也需要它:
body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
另外,我們一般不設定Content-Length. 讓我們URLSession為你做這件事。
請參閱https://stackoverflow.com/a/26163136/1271826或考慮使用像Alamofire這樣的庫,它可以讓您擺脫準備多部分請求的麻煩。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420966.html
標籤:
