【问题标题】:How to access a file after it was uploaded with Dropzone.js and PHP使用 Dropzone.js 和 PHP 上传文件后如何访问文件
【发布时间】:2020-02-19 08:27:48
【问题描述】:

我想在通过 dropzone.js (v5) 和 PHP 上传到服务器后访问文件,即我想检索文件 URL。我怎样才能得到它?

form.php:

<form action="upload.php" class="dropzone" enctype="multipart/form-data">
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
</form>

<script src="/js/dropzone.js"></script>
<script>
    Dropzone.autoDiscover = false;
    $('.dropzone').dropzone({
        init: function () {
            this.on("complete", function (file) {
                runthisfunction();
            }) // end on complete
        }
    }); 
</script>

上传.php:

<?php
if (!empty($_FILES)) {
    $random = randomString(18);
    $tempFile = $_FILES['file']['tmp_name'];          
    $name = $_FILES['file']['name'];
    $fileExt = strtolower(substr(basename($name), strrpos(basename($name), ".") + 1)); 
    $newname = $random.'.'.$fileExt;
    move_uploaded_file($tempFile,"images/$newname");
} // end if files not empty
?>

我已尝试通过文件对象检索上传的文件 URL,但没有成功:

this.on("complete", function (file) {
    console.log(file);
    console.log(file.dataURL);
    console.log(file.name);
}) // end on complete

由于该文件是使用 PHP 上传并在 upload.php 中重命名的,我相信我需要以某种方式将此文件名“发布”到另一个文件,然后将其取回。我该怎么做?

【问题讨论】:

  • 您的 PHP 脚本可能只需要在完整回调函数的 file 参数中使用您希望能够访问的任何数据进行响应?

标签: php ajax dropzone.js dropzone


【解决方案1】:

您对需要从服务器取回文件名的直觉是正确的。有一个simple example in the Dropzone FAQ 显示了基本思想。

1) 您的服务器必须响应上传 POST 并提供文件放置位置的详细信息 - 例如 URL、文件名、路径等。因此,在您的情况下,在 PHP 代码的末尾,您需要做类似的事情:

// ... rest of your PHP ...
move_uploaded_file($tempFile,"images/$newname");

// Let the browser/JS know we are sending a JSON response back.  Make sure there 
// is no output before this.
header('Content-type: application/json');
echo json_encode([
    'status' => 'OK',  // Not required, but maybe useful
    'image'  => "images/$newname",
]);

2) 在您的 JS 中,您需要接受来自服务器的响应,并对其进行处理。 Dropzone 文档显示the success event:

文件已成功上传。获取服务器响应作为第二个参数。

这听起来像是我们需要的。因此,将您的 complete 处理程序替换为 success 处理程序,并添加第二个参数:

this.on("success", function (file, response) {
    console.dir(response);
    // response.image will be the relative path to your uploaded image.
    // You could also use response.status to check everything went OK,
    // maybe show an error msg from the server if not.
});

我在上面链接到的 Dropzone FAQ 项目显示使用.emit() 方法来显示图像,我对此并不熟悉,文档中似乎也没有描述。试试看,也许这有效并适合您的需求。如果没有,您可以执行以下操作:

// Maybe you have an <img class='thumbnail'> in your HTML, ready to show the upload
$('.thumbnail').attr('src', response.image).fadeIn();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2019-10-01
    • 1970-01-01
    • 2015-12-29
    • 2013-10-22
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多