【发布时间】:2022-01-12 13:44:14
【问题描述】:
我正在尝试使用 Alamofire 的多部分表单数据上传将图像从 iOS 应用程序发送到使用 Swift 的服务器。我正在使用 PHP 接收数据,但它无法以某种方式工作。我在 stackoverflow 上查找了教程和其他问题,但没有一个在 Swift 5 中,我不确定是哪个部分导致了错误。
这是应用中的 Swift 代码:
let imageData = Image!.pngData()!
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "image", fileName: "test.png", mimeType: "image/png")
print("uploading image")
}, to: url).responseJSON { response in
debugPrint(response)
}
url正确,png数据不为空。这是 PHP 中的服务器端代码(灵感来自this stackoverflow question 的答案):
<?php
// If there is no image data
if (empty($_FILES["image"])) {
$response = array("error" => "nodata");
}
// If there is data
else {
$response['error'] = "NULL";
$filename = $_FILES["image"]["name"];
$path = "D:/emailback/images/" . $filename;
if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
$response['status'] = "success";
$response['filename'] = "".$_FILES["file"]["name"];
$response['filepath'] = $path;
} else {
$response['status'] = "Failure";
$response['error'] = "".$_FILES["image"]["error"];
$response['name'] = "".$_FILES["image"]["name"];
$response['path'] = "".$path;
$response['type'] = "".$_FILES["image"]["type"];
$response['size'] = "".$_FILES["image"]["size"];
}
}
echo json_encode($response);
?>
但我在收到的回复中暗示$_FILES['image']['size'] 为零。我不确定大小是什么意思。它也没有显示它是什么类型。 $_FILES['image']['tmp_name'] 也是空的。这是我不断收到的回复:
[Result]: success({
error = 6;
name = "test.png";
path = "D:/emailback/images/test.png";
size = 0;
status = Failure;
type = "";
})
我不太确定这意味着什么以及如何解决问题。在此先感谢:)
【问题讨论】:
-
php.net/manual/en/features.file-upload.errors.php:
UPLOAD_ERR_NO_TMP_DIR - Value: 6; Missing a temporary folder.- 所以您的 PHP 似乎没有正确设置为接收任何文件上传。 -
@CBroe 我看到 Value: 6 意味着我缺少一个临时文件夹,但我不确定临时文件夹到底意味着什么,因为这是我第一次使用 PHP。有什么帮助吗?
-
在您的脚本开始之前,当 HTTP 请求被处理时,上传的文件将首先被放入一个临时目录。该临时目录的位置必须在 PHP 配置中指定,php.net/manual/en/ini.core.php#ini.upload-tmp-dir
-
谢谢!我试试看。