Nodejs and HTML5 implementation of drag and drop multiple files uploaded to the server implementation method _node.js

Source: Internet
Author: User
Tags event listener file upload json

Implementation of multiple file drag and drop upload simple node project, you can download the github, you can start downloading: https://github.com/Johnharvy/upLoadFiles/.

Unlock the download of the ZIP format package, it is recommended to run the project with Webstom, through the App.js startup project, if the hint can not find the Node.exe execution environment, please specify your Node.exe installation location. The Express frame I use here is version 3.21.2.

Let's briefly introduce how the drag-and-drop effect is achieved.

Here first look at the code:

<! DOCTYPE html>  

HTML content is simple, one shows the allowable drag range, a div block to display the contents of the uploaded file.

JS section:

Here I have a Eventutil interface object, you can also think of it as a small library of processing events, its role is to encapsulate the various browsers bound the same event different methods, in order to achieve the browser common event binding method, unified with Eventutil object to achieve, You can simply look at its implementation code, very simple.

When the browser detects three event cases dragged, "DragEnter", "DragOver", "drag" default behavior is blocked, and executes our custom event for "drag" situations.

Because we uploaded the file, so here we use the example of Formdata, through the append () to add files to the object into the queue file, uploaded to the server side will be resolved into the queue order of the Property object. Event to get the files stored in the event through "Event.dataTransfer.files".

One thing to note here is that the jquery Ajax method needs to be configured to processdata false when uploading a file object, meaning not to use the default read string operation. The reason for this is that by default, the data passed in through the date option, if it is an object (technically, as long as it is not a string), will be processed into a query string to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, you need to set to false.

When the file is uploaded successfully, the console prints "{infor:" Success "}" information.

To this end, the front-end section ends, and here we look at the node.js end of the code.

The file structure is as follows:

Let's look at the contents of the routing--app.js:

 var Express = require (' Express '); var routes = require ('./routes '); var user = require ('./
Routes/user ');
var http = require (' http ');
var path = require (' path ');
var app = Express ();
All Environments App.set (' Port ', Process.env.PORT | | 3000);
App.set (' View engine ', ' Jade ');
App.use (Express.favicon ());
App.use (Express.logger (' dev '));
App.use (Express.json ());
App.use (express.urlencoded ());
App.use (Express.methodoverride ());
App.use (App.router);
App.use (Express.static (Path.join (__dirname)));
Exports.app=app;
var uploadaction=require ("./action/fileupload");
Routed event listener UploadAction.uploadTest.uploadFile (); File upload listener//development only if (' development ' = = App.get (' env ')) {App.use (Express.errorhandler ());} app.get ('/users ', u
Ser.list); Http.createserver (APP). Listen (App.get (' Port '), function () {console.log (' Express server listening on port ' + app.get (')
Port ')); 
});

Unlike the initial app.js, I exported the App object to reuse it in the fileupload.js, then introduced the Fileupload.js module and obtained the Uploadtest object that saved all the methods of the module and invoked the UploadFile method through the interface object.

Okay, finally, let's look at the Fileupload.js file:

var multipart = require (' Connect-multiparty ');
var app=require (".. /app ");
var path = require (' path ');
var fs=require ("FS");
var App=app.app;
var uploadtest={};
function UploadFile () {
app.post ("/uploadfile", multipart (), function (req,res) {
var i=0;
while (i!= null) {
if (req.files["file" +i]) upLoad (i);
else{i= null; Res.json ({infor: "Success"});
i++;
}
Upload Queue file
function UpLoad (index) {
var filename = req.files["file" +index].originalfilename | | path.basename ( req.files["file" +index].path);
The path interface can specify the paths and file names of the files, "\ End defaults to the path, the end of the string defaults to the filename"
var TargetPath = Path.dirname ("") + '/public/uploadfiles/' + filename;
FS creates a file of the specified path and writes the contents of the read file to
fs.createreadstream (req.files["file" +index].path). Pipe (Fs.createwritestream ( TargetPath))
;} Uploadtest.uploadfile=uploadfile;
Exports.uploadtest=uploadtest;

Nodejs is always very simple and powerful, and highly invasive, which is why I like it. We see that the key code here is actually very little, I simply introduced the implementation of the file upload logic process:

• Get the filename of the uploaded file

• Set the location where the file is stored, and the file name

• Read the contents stream of the file and create a new file to write to the content stream

In order to upload multiple files, I also do some matching operation, very intuitive, not difficult to understand.

After the file is uploaded successfully, it appears under the Uploadfiles file under the public file.

The modules used in the file are recorded in Package.json and can be installed through the instruction "NPM install" by entering the Package.json's sibling directory address. If it is directly running GitHub download the project files, you do not have to install.

The above is a small set to introduce the Nodejs and HTML5 with the implementation of drag-and-drop multiple files uploaded to the server to achieve the method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.