首页 > 解决方案 > 如何在 php 中获取 http 请求上传文件名?

问题描述

function fileupload () {

    var data = new FormData(),
    PMfile = document.getElementById("PMfile").files;
    data.append("file", PMfile[0]);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "upload.php", true);
  
    xhr.send(data);
    return false;
}
<input onchange="fileupload()" type="file" id="PMfile" name="PM_file" class="form-control" required>

我想在upload.php 中获取文件名,但我试过了$filename = $_FILES['file']['name'];,但这不起作用。

标签: javascriptphpfile-uploadxmlhttprequest

解决方案


这是正确的,应该可以工作。转储整个 $_FILES 并检查你是否得到了你想要的。对我来说,它显示了这个:

Array ( [file] => Array ( [name] => example.jpg [type] => image/jpeg [tmp_name] => /tmp/phpBQOHQl [error] => 0 [size] => 48316 ) )

$_FILES['file']['name']将是这样example.jpg

但是,如果我上传的文件对于我当前的 php 设置来说太大了,我会得到 $_FILES,因为Array ( ) 它是空的,并且在 apache 日志中我有:

[Tue Jul 07 21:04:25.535907 2020] [:error] [pid 7729] [client 127.0.0.1:37234] PHP Warning:  POST Content-Length of 21138710 bytes exceeds the limit of 8388608 bytes in Unknown on line 0, referer: http://localhost/a.php

所以我的猜测是 - 代码是正确的(如果 js/html 中没有错误,你不会向我们展示)但上传有错误 - 检查你的错误日志。


推荐阅读