Bulk drag-and-drop uploading of images using dropzone.js in ASP.

Source: Internet
Author: User
Tags button type

Say in front

Recently in an MVC album website (here), need to upload photos in bulk function, so on the Internet search related plug-ins, the occasional opportunity to find dropzone.js, tried a bit completely in line with my requirements, and the style is very satisfied, so in my project used this plugin. In the process of using the discovery of Chinese-related documents less, said more are tears, bite the bullet to see the official website, originally English is not well, can only look at the word side use, so there is this article, mainly summarizes in the use of dropzone in the encounter of some problems and detailed use of steps.

What's dropzone.js?

Dropzone.js is an open source library that provides drag-and-drop file uploads and image previews. It is lightweight and does not depend on any other libraries (such as jquery), and is highly customizable, official website here. First of all, because this is a plugin based on HTML APIs, the following browsers are supported:

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

Note: If your customer is still using a browser below IE10, then this article may not be suitable for you, or you can persuade a customer to give up using IE and may get a different experience.

Directly on a few, we first see if you meet your requirements, and then decide whether to use.

  

  

  

How do I download it?

The website provides the JS download, here, this is just a JS, does not include the relevant style, pictures, etc., so it is recommended to download the full package from GitHub, address here. The simplest way to download this project is to use the download zip on the right, which will automatically pack all the files into a zip file, and the downloads folder is what we need, including JS, images, CSS and other files.

How do I use it?

Dropzone website provides demo, but the demo does not implement the ability to upload multiple images at once, and also does not provide the server-side C # code. So I summed up the steps used, convenient for later reuse. Here I put the use of methods into the front-end and back-end code, the front-end is mainly the file reference, Dropzone initialization, and related property event description. The backend means the action in MVC, and the main function is to get the file from the request and store it on the server. Let me take a very careful way.

Front End

1. Reference file

First of all, it is certain to first download the file classification into their own projects, so that the future management, but also in line with international practice.

Then you need to reference it in the page, and the code referenced 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>

You see I quoted three files, where jquery files are not required, because at the beginning of the article also introduced Dropzone is a separate library, do not need to rely on jquery, I for the convenience of operation, so here quoted a bit, see personal choice.

2. Create form elements  

<!--class= "Dropzone" uses dropzone style styles in the referenced CSS--><form action= "/"    class= "Dropzone"    enctype= " Multipart/form-data "    id=" My-dropzone "    method=" POST ">    <!--upload a picture, you need to submit the data at the same time, here to do a demo--    Html.hidden ("Hidalbumid") </form><div>    <!--upload button to provide multiple images one-time upload function--    <button type= " Submit "id=" Submit-all "disabled=" disabled "> uploads </button></div>

3. Initialize the Dropzone and add properties and events

<script>//dropzone initialization, Mydropzone is the ID of the form Dropzone.options.myDropzone = {//Specify the path to upload the picture URL: "@Url. Action (" Batchupload "," photoupload "),//Add a link to upload cancel and delete the preview picture, not added by default addremovelinks:tr UE,//Turn off the automatic upload function, the default is True will automatically upload//That is, add a picture to the server to send a request autoprocessqueue:false,//            Allows uploading multiple photos uploadmultiple:true,//upload the maximum number of files, tested by default to 2, Pit AH//Remember to modify the Web. config limit upload file size section paralleluploads:100, Init:function () {var Submitbutton = Document.queryselector ("#submit -all ") Mydropzone = this;                    Closure//Add click event Submitbutton.addeventlistener for the upload button ("click", Function () {                Upload All pictures manually mydropzone.processqueue ();                }); When adding a picture after the event, the upload button recovers the available This.on ("Addedfile", function () {$ ("#submit-all"). Removeattr ("Dis Abled ");               }); When uploading the completed event, the accepted data is in JSON format This.on ("Complete", function (data) {if (this.getuploadingfile S (). length = = 0 && this.getqueuedfiles (). Length = = 0) {var res = eval (' (' + data.xhr.res                        (Ponsetext + ') ');                        var msg; if (res. Result) {msg = "Congratulations, uploaded successfully" + Res. Count + "Photos!                        "; } else {msg = "Upload failed, the reason for the failure is:" + Res.                        Message;                        } $ ("#message"). Text (msg);                    $ ("#dialog"). Dialog ("Open");                }                }); Delete the picture event, when the uploaded picture is empty, make the upload button unavailable status This.on ("Removedfile", function () {if (this.getaccepted                    Files (). Length = = 0) {$ ("#submit-all"). attr ("Disabled", true);            }                });     }   };</script> 

So the front end of the work is basically completed, the following look at the back end of the work.

★ Back end

The backend features are simple to receive files, then save the data to the server and return the 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 = ""; Here is the//int albumID = string that gets the data in the hidden field.    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});}

Summarize

Through this practice, just found that the powerful HTML APIs, Dropzone is through the invocation of APIs to realize the function, now their own technology from all aspects have been lagging a lot, and later have to seize their spare time, more personal projects, in order to continue to improve in practice. Because of their own understanding of the relevant technology is not deep, there will be omissions in the text, but also please criticize correct.

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

This article from: http://www.cnblogs.com/hdkn235/p/3887556.html

Bulk drag-and-drop uploading of images using dropzone.js in ASP.

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.