我有以下 JS 代码,用于根据其路径上传图像:
var data = new FormData();
data.append('fileName', fileName);
data.append('file', file);
$.ajax({
url : dbPath + "upload-file.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
这是我的upload-image.php脚本:
<?php
$fileName = $_POST['fileName'];
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "Sorry, your file is larger than 20 MB. Upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr."".$fileName;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
上传文件(例如 JPG 图像)时一切正常,但我的目的是使用:
data.append('fileName', fileName);
只需将文件名和扩展名附加到 myFormData并获取如下文件 URL:
https://example.com/_json/uploads/03aC8qsIk4hanngqO3G4_fileName.jpg
但是我的 PHP 脚本中的 $fileName 变量会触发 error_log 行Undefined index fileName in line xx,那么有没有办法上传文件,获取其名称和扩展名并将其附加到我的 PHP 脚本生成的文件 URL 中?
我希望我的问题很清楚,我想要做的只是对任何类型的文件进行一般的 Ajax 自动上传,而不仅仅是图像,并根据随机字符串 + 其名称和扩展名(如 .png, .mp4、.pdf 等)。
米琪卡哇伊