Asp.Net Core - Not Able to Upload Files From Dropzone JS

Viewed 602

I am using asp.net core 2.2 with dropzone js.

I am trying to submit a form along with the files contained in dropzone js.

I have an input file field (can be hidden or not hidden). I want to assign dropzone files to this field and submit it. But the Forms field is always null.

Here is the code:

MVC Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(ViewModels.Photo model)
{
    var files = HttpContext.Request.Form.Files; // this is also empty
    ....
}

MVC Model:

public class Photo
{
    ...

    public List<IFormFile> Files { get; set; }
}

HTML:

<form asp-action="Add" asp-controller="Photos" method="post" id="addForm" enctype="multipart/form-data">
    <div class="dropzone">
        <input asp-for="Files" type="file" multiple hidden/>
    </div>
    <button type="submit">Submit</button>
</form>

JS:

var e = "#addForm",
var t = new Dropzone(e, {
    maxFilesize: 1,
    acceptedFiles: ".png,.jpg,.jpeg",
    uploadMultiple: false,
    autoProcessQueue: false
});
t.on("addedfile", function (o) {
    $("#Files").files = t.files;
})
2 Answers

I managed to get things working and it was a minor fix.

I changed below code

$("#Files").files = t.files;

to

$("#Files").files = t.hiddenFileInput.files;

t.files is an array of files being captured by dropzone where as t.hiddenFileInput.files is an FileList object of files being captured by dropzone.

The $("#Files").files is also an FileList object that's why t.files was not working due to type mismatch.

Now it submits form fields along with files with default submit mechanism.

Related