为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
LEATH 2022-07-16 18:46:31
我有以下 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 等)。
查看完整描述

1 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

我已经想通了,感谢所有评论,我不得不将其附加fileName到我的FormData()并编辑我的 PHP 脚本,如下所示:


JS:


function uploadFile() {

var dbPath = '<?php echo $DATABASE_PATH ?>';

    var file = $("#file")[0].files[0];

    var fileName = file.name;

    console.log('FILE NAME: ' + fileName);


    Swal.fire({icon: 'success', title: 'Loading...', showConfirmButton: false })


    var data = new FormData();

    data.append('file', file);

    data.append('fileName', fileName); <!-- ADDED THIS LINE


    $.ajax({

        url : dbPath + "upload-file.php?fileName=" + fileName, <!-- ADDED THIS LINE

        type: 'POST',

        data: data,

        contentType: false,

        processData: false,

        mimeType: "multipart/form-data", <!-- ADDED THIS LINE

        success: function(data) {

            Swal.close();


            var fileURL = dbPath + data;

            console.log('FILE UPLOADED TO: ' + fileURL);

            // error

            if (data.includes("ERROR:")) {

                Swal.fire({ icon: 'error', title: 'Oops...', text: data, });

            // show file data

            } else {

                $("#fileURL").val(fileURL);

                $("#viewButton").attr("href", fileURL);

                $("#viewButton").css("display", "block");

            }

        // error

        }, error: function(e) {  

            Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong: ' + e.message, });

    }});

}

我的upload-file.php脚本:


<?php include 'config.php';


if ($_FILES["file"]["error"] > 0) {

    echo "Error: " .$_FILES["file"]["error"]. "<br>";


} else {

    // Check file size

    if ($_FILES["file"]["size"] > 20485760) { // 20 MB

        echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";    

    } else { uploadImage(); }


}// ./ If



// UPLOAD IMAGE ------------------------------------------

function uploadImage() {

    // generate a unique random string

    $randomStr = generateRandomString();

    $filePath = "uploads/".$randomStr;


    // 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."_".$_POST['fileName']; <!-- ADDED THIS LINE

}

?>

现在我终于可以上传任何类型的文件并在 URL 末尾获取其名称 + 扩展名,它可以完美运行。


查看完整回答
反对 回复 2022-07-16
  • 1 回答
  • 0 关注
  • 164 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信