DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Dynamic File Upload Component in Salesforce LWC
  • How To Protect Node.js Form Uploads With a Deterministic Threat Detection API
  • How To Scan and Validate Image Uploads in Java
  • How To Use IBM App Connect To Build Flows

Trending

  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • The Evolution of Scalable and Resilient Container Infrastructure
  • Using Java Stream Gatherers To Improve Stateful Operations

Upload Files In .NET Core By Drag And Drop Using Dropzone.JS

Learn a quick and easy drag and drop took, Dropzone.js, which will allow you to quickly customize your web site, while writing minimal code.

By 
Prashant Khandelwal user avatar
Prashant Khandelwal
·
Mar. 13, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
40.2K Views

Join the DZone community and get the full member experience.

Join For Free

Mostly all web applications out there have some amazing ways to upload a single file or multiple files. While surfing on Github I found this amazing library to upload the files to the server in a unique way with a lot of configurations. It supports parallel uploads along with cancellation of the files which are in the upload queue, along with a good looking progress bar to show the progress of the upload.

I got the drag and drop to work in just 5 minutes. It is super easy and has some powerful configurations. To install Dropzone you can use the Nuget command.

PM> Install-Package dropzone

Add reference of js and CSS files on your page. To get the UI ready, use this HTML:

<div class="row">
    <div class="col-md-9">
        <div id="dropzone">
            <form action="/Home/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>


There are a few points to be noted in the above HTML. Notice the action and class attributes for the form element. You will also need the id attribute. as well. Here, the action attribute points to the ActionResult which is responsible for handling the file upload. I have pointed it to the Upload ActionResult in my controller class which accepts a parameter of the type, IFormFile. In the case of an MVC application, we would have used the HttpPostedFileBase class. Here is the complete code which handles the file upload.

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


The _environment variable you see in the above code is the instance of the IHostingEnvironment interface which I have injected into the controller. Always use the IHostingEnvironment interface to resolve the paths. You can hard code the file path, but it may not work on other platforms. The combined method returns the correct path based on the platform the code is executing. The WebRootPath property returns the path of wwwroot to the folder, and the second parameter, uploads, is then appended correctly with the path.

Now it is time to make some adjustments in the Dropzone configuration. Recall the id attribute of the form element. I named it uploader. The Dropzone library has a unique way to set the configuration. Like this:

<script>
    $(document).ready(function () {
        Dropzone.options.uploader = {
            paramName: "file",
            maxFilesize: 2,
            accept: function (file, done) {
                if (file.name == "test.jpg") {
                    alert("Can't upload a test file.");
                }
                else {
                    //Show a confirm alert and display the image on the page.
              }
           }
        };
});
</script>


You have to be a bit careful when setting this configuration. In the configuration above the paramName states the name that will be used to transfer the file. This name should be the same as the IFormFile parameter of the Upload method in the controller. In this case, I am using file and the same has to be there in the param of the Upload method. If the names mismatch, the files will not be uploaded. The other parameter I am using is the maxFileSize and is very much self-explanatory. I have set the size to be 2 MB and thus, because of this configuration, any file above this limit will not be uploaded. 

All the other files were uploaded successfully except one file which is 4.32 MB and is way beyond the limit I set in my Dropzone configuration. If you hover the file, you will see why it failed.

This is the simplest approach by which you can have drag and drop upload support in your applications. The configuration I am using here is the simplest and minimalistic configuration that can get you started in no time. There are some more powerful configurations like parallelUploads and uploadMultiple that you should also look into and use.

Upload Drops (app)

Published at DZone with permission of Prashant Khandelwal, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Dynamic File Upload Component in Salesforce LWC
  • How To Protect Node.js Form Uploads With a Deterministic Threat Detection API
  • How To Scan and Validate Image Uploads in Java
  • How To Use IBM App Connect To Build Flows

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!