I'm trying to implment a file upload feature for users where they can upload multiple files at once. I'm using dropzone.js on the client side and C# in the back end. I'm using MVC razor views and I have view where the user inputs their details and upload files within the same page. So I've gone ahead and created the following methods
[HttpPost]
public async Task<ActionResult> UploadedFile(int? id)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
if (file != null && file.ContentLength > 0)
{
//upload file here
//file gets uploaded successfully
}
}
return new EmptyResult();
}
I also need to store model details into the DB which are done in another method as follows
public async Task<ActionResult> SaveToDb(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
//Store to db here
int? id = viewModel.User.UserId;
//redirect to home page if everything is ok
}
return View(viewModel);
}
Now my question is I need to run the SaveToDb
before UploadedFile
method because I want to pass the int? id
as a param because I use it at the end of the file name. I really can't seem to figure out how to go about this. My client jQuery
looks like this:
<script>
Dropzone.autoDiscover = false;
var myDropZone = new Dropzone("#dZUpload",{
url: "/Home/UploadedFile",
autoProcessQueue: false
});
$("#submit-all").on('click', function () {
myDropZone.options.autoProcessQueue = true;
myDropZone.processQueue();
});
myDropZone.on("addedfile", function (file) {
var removeButton = Dropzone.createElement("<button class='btn btn-danger'>Remove File</button>");
var dLink = myDropZone;
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
dLink.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
</script>
Note: #submit-all
button also submits the entire form