A simple Node project that implements multi-file drag-and-drop upload can be downloaded on github. You can download it first: https://github.com/Johnharvy/upLoadFiles/.
Unlock the downloaded zip format package. It is recommended to use webstom to run the project and start the project through app.js. If the prompt is that the node.exe execution environment cannot be found, please specify your node.exe installation location. The express framework I use here is version 3.21.2.
Let’s briefly introduce how the drag and drop effect is achieved.
Let's look at the code first:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><script src="js/jquery.js"></script><script src="js/EventUtil.js"></script><title>uploadFile</title><style>#a1{width:100px;height:100px;background: #aaaaaa;text-align:center;line-height:100px;color:rgba(81, 49, 202, 0.72);margin:150px auto;}</style></head><body><div id="a1">Drag to this</div><div id="out-input"></div><script>var a1=document.getElementById("a1");function handleEvent(event){var info ="",output= document.getElementById("out-input"),files,i,len;EventUtil.preventDefault(event); //Default behavior of blocking events var formData =new FormData();if(event.type == "drop"){files=event.dataTransfer.files;i = 0;len= files.length;while( i< len){info += files[i].name +"("+ files[i].type + "," +files[i].size +"bytes)<br/>";formData.append("file"+i,files[i]);i++;}output.innerHTML = info;$.ajax({type:"post",url:"/uploadFile",data:formData,async: false,cache: false,contentType: false,processData: false, //Here we specify the operation to not read the string by default for uploading data success:function(rs){console.log(rs);},error:function(r){alert("A file upload error!");}});}}EventUtil.addHandler(a1, "dragover", handleEvent);EventUtil.addHandler(a1, "drop", handleEvent);EventUtil.addHandler(a1, "drop", handleEvent);</script></body></html>The html content is very simple, one displays the allowed drag range, and one is used to display the content of the uploaded file.
Js part:
Here I have prepared an EventUtil interface object, which you can also regard as a small library for handling events. Its function is to encapsulate different methods for binding the same events in each browser. In order to implement the common event binding methods of each browser, it is uniformly implemented using the EventUtil object. You can simply look at its implementation code, which is very simple.
When the browser detects three events of drag, "drager", "dragover", and "drag" default behavior will be blocked, and our custom events will be executed when the "drag" situation is "drag".
Because we upload a file, we use the FormData instance here. Add a file to the object through append() to become a queue file. After uploading to the server, it will be parsed into attribute objects in queue order. In the event, the files stored in the event are retrieved through "event.dataTransfer.files".
Another thing to note here is that the ajax method of jquery needs to configure processData to false when uploading file objects, which means not using the default reading string operation. The reason is that by default, if the data passed in through the data option is an object (technically speaking, as long as it is not a string), it will be processed and converted 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 it to false.
After the file upload is successfully uploaded, the console will print the "{infor:"success"}" information.
At this point, the front-end part ends. Let’s take a look at the code on the Node.js side.
The file structure is as follows:
Let's first look at the content in the route - 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 environmentsapp.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");//Routing event listening uploadAction.uploadTest.uploadFile();//File upload upload onlyif ('development' == app.get('env')) {app.use(express.errorHandler());}app.get('/users', user.list);http.createServer(app).listen(app.get('port'), function(){console.log('Express server listening on port ' + app.get('port'));});There are several differences from the initial app.js. I exported the app object to reuse it in fileUpload.js, and then introduced the fileUpload.js module, and obtained the uploadTest object that saves all methods of the module through this interface object and called the uploadFile method.
OK, 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"});return;}i++;}//Upload queue file function upLoad(index){var filename = req.files["file"+index].originalFilename || path.basename(req.files["file"+index].path);//path interface can specify the path and file name of the file. "/The ending is the path, and the ending of the string is the file name by default"var targetPath = path.dirname("") + '/public/uploadFiles/' + filename;//fs creates a file with a specified path and writes the read file content to fs.createReadStream(req.files["file"+index].path).pipe(fs.createWriteStream(targetPath));}});} uploadTest.uploadFile=uploadFile;exports.uploadTest=uploadTest;nodeJs are always very simple and powerful, and highly creative, which is why I like it. We see that there are actually very few key codes here. I will briefly introduce the logical process of implementing file upload:
• Obtain the file name of the uploaded file
•Set the file storage location and file name
•Read the content stream of the file and create a new file to write the content stream
In order to upload multiple files, I also did some matching operations, which are very intuitive and not difficult to understand.
After the file is uploaded successfully, it will appear under the uploadFiles file under the public file.
The modules used in the file are recorded in package.json. They can be installed through the command "npm install" by entering the directory address of package.json's simultaneous level. If you run the project files downloaded on github directly, you don’t need to install them anymore.
The above is the implementation method of combining NodeJS and HTML5 to upload multiple files to the server. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!