jQuery - 将文件名附加到 FormData 并在 PHP 脚本中获取它

我有以下 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 等)。


LEATH
浏览 167回答 1
1回答

米琪卡哇伊

我已经想通了,感谢所有评论,我不得不将其附加fileName到我的FormData()并编辑我的 PHP 脚本,如下所示:JS:function uploadFile() {var dbPath = '<?php echo $DATABASE_PATH ?>';&nbsp; &nbsp; var file = $("#file")[0].files[0];&nbsp; &nbsp; var fileName = file.name;&nbsp; &nbsp; console.log('FILE NAME: ' + fileName);&nbsp; &nbsp; Swal.fire({icon: 'success', title: 'Loading...', showConfirmButton: false })&nbsp; &nbsp; var data = new FormData();&nbsp; &nbsp; data.append('file', file);&nbsp; &nbsp; data.append('fileName', fileName); <!-- ADDED THIS LINE&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url : dbPath + "upload-file.php?fileName=" + fileName, <!-- ADDED THIS LINE&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; data: data,&nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp; &nbsp; &nbsp; &nbsp; mimeType: "multipart/form-data", <!-- ADDED THIS LINE&nbsp; &nbsp; &nbsp; &nbsp; success: function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Swal.close();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var fileURL = dbPath + data;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('FILE UPLOADED TO: ' + fileURL);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // error&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (data.includes("ERROR:")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Swal.fire({ icon: 'error', title: 'Oops...', text: data, });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // show file data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#fileURL").val(fileURL);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#viewButton").attr("href", fileURL);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#viewButton").css("display", "block");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // error&nbsp; &nbsp; &nbsp; &nbsp; }, error: function(e) {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong: ' + e.message, });&nbsp; &nbsp; }});}我的upload-file.php脚本:<?php include 'config.php';if ($_FILES["file"]["error"] > 0) {&nbsp; &nbsp; echo "Error: " .$_FILES["file"]["error"]. "<br>";} else {&nbsp; &nbsp; // Check file size&nbsp; &nbsp; if ($_FILES["file"]["size"] > 20485760) { // 20 MB&nbsp; &nbsp; &nbsp; &nbsp; echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; } else { uploadImage(); }}// ./ If// UPLOAD IMAGE ------------------------------------------function uploadImage() {&nbsp; &nbsp; // generate a unique random string&nbsp; &nbsp; $randomStr = generateRandomString();&nbsp; &nbsp; $filePath = "uploads/".$randomStr;&nbsp; &nbsp; // upload image into the 'uploads' folder&nbsp; &nbsp; move_uploaded_file($_FILES['file']['tmp_name'], $filePath);&nbsp; &nbsp; // echo the link of the uploaded image&nbsp; &nbsp; echo $filePath;}// GENERATE A RANDOM STRING ---------------------------------------function generateRandomString() {&nbsp; &nbsp; $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';&nbsp; &nbsp; $charactersLength = strlen($characters);&nbsp; &nbsp; $randomString = '';&nbsp; &nbsp; for ($i = 0; $i<20; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $randomString .= $characters[rand(0, $charactersLength - 1)];&nbsp; &nbsp; }&nbsp; &nbsp; return $randomString."_".$_POST['fileName']; <!-- ADDED THIS LINE}?>现在我终于可以上传任何类型的文件并在 URL 末尾获取其名称 + 扩展名,它可以完美运行。
打开App,查看更多内容
随时随地看视频慕课网APP