简体   繁体   English

如何在JavaScript中将PHP文件名分配为变量值?

[英]How do I assign a PHP file name as a variable value in JavaScript?

I use this html5 script in order to get file information in my php form. 我使用此html5脚本来获取我的php格式的文件信息。 What I want is not to upload the file but only get the filename without uploading the file. 我想要的不是上传文件,而是仅获取文件名而不上传文件。 Is it possible? 可能吗?

Here is the script : 这是脚本:

<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object

// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
  output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
              f.size, ' bytes, last modified: ',
              f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
              '</li>');
 }
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

No, you can't know the file name without uploading it and checking $_FILES array. 不,如果不上传文件并检查$_FILES数组,就无法知道文件名。
You can however issue an AJAX request that will upload the file and return the filename so you can add it in your views 但是,您可以发出AJAX请求,该请求将上传文件并返回文件名,以便您可以将其添加到视图中

You already have filename in f.name javascript variable. 您已经在f.name javascript变量中包含了文件名。 If you want to send it to server, just put it in a hidden input inside your form. 如果要将其发送到服务器,只需将其放在表单内部的隐藏输入中即可。 Or you can send this value using ajax request. 或者,您可以使用ajax请求发送此值。

Given the following form: 给出以下形式:

<form name="myForm" action="send.php">
    <input type="file" id="fileSelect">
    <input type="hidden" name="filename">
    <input type="submit">
</form>

To stop the file actually being uploaded, don't give the file input field a name attribute. 要停止实际上传的文件,请不要为文件输入字段指定name属性。 Instead, you create a hidden input field, and when the user selects a file, populate that field with the file name, for example: 而是创建一个hidden输入字段,然后在用户选择文件时,使用文件名填充该字段,例如:

<script>
    var fileSelect = document.getElementById('fileSelect');

    var handleFileSelect = function(e) {
        var files = e.target.files;
        if(files.length === 1) {
            document.forms.myForm.filename.value = files[0].name;
        }
    };

    fileSelect.addEventListener('change', handleFileSelect, false);
</script>

Now when the user submits the form, you can get the filename using $_GET['filename'] . 现在,当用户提交表单时,您可以使用$_GET['filename']获得文件$_GET['filename']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM