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

Source: Internet
Author: User

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.

Dropzone.js What 's that?

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 to download?

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 files<Linkhref= "~/content/css/dropzone.css"rel= "stylesheet" />//jquery file, not required<Scriptsrc= "~/scripts/jquery-1.8.2.min.js"></Script>//js File<Scriptsrc= "~/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 the Dropzone style style in the referenced CSS -<formAction="/"class= "Dropzone"enctype= "Multipart/form-data"ID= "My-dropzone"Method= "POST">    <!--when uploading 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 for one-time upload function -    <Buttontype= "Submit"ID= "Submit-all"Disabled= "Disabled">Upload</Button></Div>

3. Initialize the Dropzone and add properties and events

<script>//dropzone initialization, Mydropzone is the ID of the formDropzone.options.myDropzone = {            //specify the path to upload picturesURL: "@Url. Action (" Batchupload "," Photoupload ")",            //Add upload cancel and delete preview picture link, default not addedAddremovelinks:true,            //Turn off Auto-upload, by default true will automatically upload            //That is, add a picture to send a request to the serverAutoprocessqueue:false,            //allow multiple photos to be uploadedUploadmultiple:true,            //the maximum number of files per upload, tested by default to 2, pit AH            //Remember to modify the Web. config limit upload file size sectionparalleluploads:100, Init:function () {                varSubmitbutton = Document.queryselector ("#submit-all") Mydropzone= This;//Closure                //Add a Click event for the upload buttonSubmitbutton.addeventlistener ("click",function () {                    //upload all pictures manuallyMydropzone.processqueue ();                }); //when you add a picture after the event, the upload button resumes available                 This. On ("Addedfile",function () {                    $("#submit-all"). Removeattr ("Disabled"));                }); //when uploading completed events, the accepted data is in JSON format                 This. On ("complete",function(data) {if( This. Getuploadingfiles (). Length = = 0 && This. Getqueuedfiles (). length = = 0) {                        varres = eval (' (' + data.xhr.responseText + ') '); varmsg; if(Res. Result) {msg= "Congratulations, uploaded successfully" + Res. Count + "Photos! "; }                        Else{msg= "Upload failed, the reason for failure is:" +Res.                        Message; }                        $("#message"). Text (msg); $("#dialog"). Dialog ("Open"));                }                }); //Delete picture events, make the upload button unavailable when the uploaded picture is empty                 This. On ("Removedfile",function () {                    if( This. Getacceptedfiles (). 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] PublicActionResult batchupload () {BOOLissavedsuccessfully =true; intCount =0; stringmsg =""; stringFileName =""; stringFileExtension =""; stringFilePath =""; stringFilenewname =""; //This is to get the data in the hidden field//int albumid = string.    IsNullOrEmpty (request.params["Hidalbumid"])? //0:int. Parse (request.params["Hidalbumid"]);    Try    {        stringDirectoryPath = Server.MapPath ("~/content/photos"); if(!directory.exists (DirectoryPath))        Directory.CreateDirectory (DirectoryPath); foreach(stringFinchrequest.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; }    returnJson (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

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.