使用 dropzone.js 拖放文件上传

File upload drag and drop with dropzone.js

我正在使用 dropzone.js 实现拖放功能来上传文件。它正在工作。我不明白的是为什么我不能限制文件大小和文件扩展名。我想我有它的代码,但它就是做不到。

在 cshtml 页面中:

<script src="~/js/dropzone.js"></script>
<link href="~/css/dropzone.css" rel="stylesheet" />

<script>
    Dropzone.options.dropzone = {
        paramName: "file", // The name that will be used to transfer the file
        maxFilesize: 2, // MB
        acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg",
        accept: function (file, done) {
            if (file.name == "justinbieber.jpg") {
                done("Naha, you don't.");
            }
            else { done(); }
        }
    };
</script>

<div class="row">
    <div class="col-md-9">
        <div id="dropzone">
            <form action="Upload" class="dropzone needsclick dz-clickable" id="uploader">
                <div class="dz-message needsclick">       
                    Drop files here or click to upload.<br>
                </div>
            </form>
        </div>
    </div>
</div>

在家庭控制器中

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    var uploads = Path.Combine(_environment.WebRootPath, "images");
    if (file.Length > 0)
        using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
            await file.CopyToAsync(fileStream);

    return RedirectToAction("About");
}

我的意思是,代码是由他们提供的,我有 dropzone.js 和 dropzone.css 就像他们告诉我们的那样,而且仍然......事情是,它正在工作。它上传,转到后面的代码。一切。我就是无法应用这些限制,即使它们存在...

有人知道这里发生了什么吗?

您在与表单不同的 Dropzone 上设置了选项。 From the docs:

Dropzone will find all form elements with the class dropzone, automatically attach itself to it, and upload files dropped into it to the specified action attribute.

因此您的 <form> 与 class dropzone 自动设置为 Dropzone。

Again from the docs,要在 Dropzone 上设置选项,您可以使用 Dropzone.options.myAwesomeDropzone = {},其中:

// "myAwesomeDropzone" is the camelized version of the HTML element's ID

在您的代码中,您使用的是 Dropzone.options.dropzone,因此您将这些选项应用到 ID 为 dropzone 的 Dropzone。在您的 HTML 中,那是 <div>,而不是您现有的 <form> Dropzone。因此,当您将文件拖放到 <form> 上时,您指定的那些选项并不相关 - 它们用于不同的 Dropzone(实际上从未实例化)!

摆脱你的 <div id="dropzone">,并将你的选项上的标识符更改为 Dropzone.options.uploader,以便它们适用于你的表单 Dropzone。