In ASP. net mvc, Dropzone. js is used to implement batch drag and drop upload of images,

Source: Internet
Author: User

In ASP. net mvc, Dropzone. js is used to implement batch drag and drop upload of images,

Mentioned above

Recently, I was working on an MVC album website (here) and needed to upload photos in batches. So I searched for related plug-ins on the Internet and found Dropzone by chance. js. I tried this plug-in my project because it fully complies with my requirements and the style is quite satisfactory. In the process of use, I found that there were few documents related to Chinese characters, and many of them were tears. I tried to read the official website with my head. I had to check words and use them, as a result, this article mainly summarizes some problems encountered in the use of Dropzone and detailed steps for use.

Dropzone. jsWhat is it?

Dropzone. js is an open-source library that provides drag-and-drop file upload and image preview. It is lightweight and does not rely on any other libraries (such as jQuery), and is highly customizable. The official website is here. First of all, this is because it is a plug-in based on Html APIs, so there are the following browser support:

  • Chrome 7 +
  • Firefox 4 +
  • IE 10 +
  • Opera 12 + (Version 12 for MacOS is disabled because their API is buggy)
  • Safari 6 +

NOTE: If your customers are still using browsers earlier than IE10, this article may not be suitable for you, or you can persuade the customer to give up using IE, which may lead to a different experience.

Just a few images. Let's see if it meets your requirements before deciding whether to use it.

  

  

  

How to download?

Download the js provided on the official website. Here, this is just a js, excluding related styles and images. We recommend that you download the complete package from Github at this address. The simplest way to Download this project is to use Download ZIP on the right. All files are automatically packaged into zip files and downloaded. The downloads folder is what we need, including js, images, css, and other files.

How to use it?

The dropzone official website provides a Demo, but the Demo does not implement the function of uploading multiple images at a time, and does not provide Code related to server C. So I summarized the steps to facilitate reuse in the future. Here I divide the usage into front-end and back-end code. The front-end mainly involves file reference, dropzone initialization, and related attribute event description. The backend is the Action in MVC. The main function is to get files from the Request and store them in the server. Let me explain it in detail.

Front end

   1. Reference a file

First of all, you must first classify the downloaded files into your own projects. This facilitates future management and complies with international practices.

Then you need to reference it on the page. The referenced code is as follows:

// Style File <link href = "~ /Content/css/dropzone.css "rel =" stylesheet "/> // jQuery file, not required <script src = "~ /Scripts/jquery-1.8.2.min.js "> </script> // js file <script src = "~ /Scripts/dropzone. js "> </script>

As you can see, I have referenced three files. Among them, jQuery files are not necessary, because at the beginning of this article, we also introduced that dropzone is an independent library and does not need to depend on jQuery. For ease of operation, so I quoted it here. I have selected it.

2. Create a form Element  

<! -- Class = "dropzone" Use the style that comes with dropzone in the referenced CSS --> <form action = "/" class = "dropzone" enctype = "multipart/form-data" id = "my-dropzone" method = "post"> <! -- The data that needs to be submitted at the same time when uploading an image. Here is a demonstration --> @ Html. Hidden ("hidAlbumId") </form> <div> <! -- Upload button, provides the one-time upload function for multiple images --> <button type = "submit" id = "submit-all" disabled = "disabled"> upload </button> </div>

3. initialize Dropzone and add properties and events

<Script> // initialization of Dropzone. myDropzone is the id Dropzone of form. options. myDropzone = {// specify the url of the image to be uploaded: "@ Url. action ("BatchUpload", "PhotoUpload") ", // Add the link for canceling upload and deleting preview images. addRemoveLinks: true is not added by default, // disable the automatic upload function, by default, "true" indicates that an image is automatically uploaded. // Add an image and send a request to the server. autoProcessQueue: false. // you can upload multiple photos. uploadMultiple: true, // The maximum number of files uploaded each time. The default value is 2. // remember to modify the web. section in config that limits the size of the uploaded file parallelUploads: 100, init: function () {var submitButton = Document. querySelector ("# submit-all") myDropzone = this; // closure // Add and click the event submitButton for the upload button. addEventListener ("click", function () {// manually upload all images to myDropzone. processQueue () ;}); // when an image is added, the upload button is available again. on ("addedfile", function () {$ ("# submit-all "). removeAttr ("disabled") ;}); // when the upload is complete, the received data is in JSON Format this. on ("complete", function (data) {if (this. getUploadingFiles (). length = 0 & this. getQueued Files (). length = 0) {var res = eval ('+ data. xhr. responseText + '); var msg; if (res. result) {msg = "congratulations, uploaded successfully" + res. count + "photo! ";} Else {msg =" Upload Failed because: "+ res. message;} $ ("# message "). text (msg); $ ("# dialog "). dialog ("open") ;}}); // deletes an image event. When the uploaded image is empty, the upload button is unavailable. this. on ("removedfile", function () {if (this. getAcceptedFiles (). length = 0) {$ ("# submit-all "). attr ("disabled", true) ;}}};</script>

In this way, the front-end work is basically completed. Let's take a look at the back-end work.

★Backend

The backend function is quite simple, that is, it receives files, saves the data to the server, and returns JSON data. The Code is as follows:

[HttpPost] public ActionResult BatchUpload () {bool isSavedSuccessfully = true; int count = 0; string msg = ""; string fileName = ""; string fileExtension = ""; string filePath = ""; string fileNewName = ""; // obtain the data in the hidden domain. // int albumId = string. isNullOrEmpty (Request. params ["hidAlbumId"])? // 0: int. Parse (Request. Params ["hidAlbumId"]); try {string directoryPath = Server. MapPath ("~ /Content/photos "); if (! Directory. Exists (directoryPath) Directory. CreateDirectory (directoryPath); foreach (string f in Request. Files) {HttpPostedFileBase file = Request. Files [f]; if (file! = Null & file. contentLength> 0) {fileName = file. fileName; fileExtension = Path. getExtension (fileName); fileNewName = Guid. newGuid (). toString () + fileExtension; filePath = Path. combine (directoryPath, fileNewName); file. saveAs (filePath); count ++ ;}} catch (Exception ex) {msg = ex. message; isSavedSuccessfully = false;} return Json (new {Result = isSavedSuccessfully, Count = count, Message = msg });}

Summary

Through this practice, we just found that Html APIs is powerful, and Dropzone is implemented by calling APIs. Now our technology lags behind in many aspects, in the future, you must hurry up and do more personal projects in your spare time to continue improving in practice. Due to your lack of deep understanding of the relevant technologies, you may find omissions in this article. Please criticize and correct them.

Reference

Http://www.dropzonejs.com/

Http://www.dropzonejs.com/bootstrap.html

Http://stackoverflow.com/questions/18059128/dropzone-js-uploads-only-two-files-when-autoprocessqueue-set-to-false

Http://stackoverflow.com/questions/18048825/how-to-limit-the-number-of-dropzone-js-files-uploaded

Http://venkatbaggu.com/file-upload-in-asp-net-mvc-using-dropzone-js-and-html5/

Http://stackoverflow.com/questions/16050965/using-dropzone-js-in-asp-net

Https://github.com/enyo/dropzone/wiki/Upload-all-files-with-a-button




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.