Home>Article>Web Front-end> How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server

How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server

高洛峰
高洛峰 Original
2017-01-12 16:51:40 1611browse

A simple Node project that implements drag-and-drop upload of multiple files can be downloaded from github. You can download it first: https://github.com/Johnharvy/upLoadFiles/.

Unzip the downloaded zip format package. It is recommended to use webstom to run the project and start the project through app.js. If it prompts 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 effect is achieved.

Let’s look at the code first:

      uploadFile  
拖拽到此

The html content is very simple, one shows the allowed drag range, and the other is a div block used to display the content of the uploaded file.

Js part:

Here I have prepared an EventUtil interface object. You can also think of it as a small library for processing events. Its function is to encapsulate Different methods for binding the same events in various browsers are shown. In order to implement the event binding method common to all browsers, the EventUtil object is used to implement it uniformly. You can simply take a look at its implementation code. It is very simple.

When the browser detects the three event situations of dragging, the default behaviors of "dragenter", "dragover" and "drag" will be blocked. When it is the "drag" situation, our Custom events.

Because we are uploading files, an instance of FormData is used here. Files are added to the object through append() to become a queue file. After uploading to the server, it will be parsed in queue order. Properties object. In the event, "event.dataTransfer.files" is used to obtain the files stored in the event.

Another thing to note here is that jquery's ajax method needs to configure processData to false when uploading file objects, which means that the default operation of reading strings is not used. The reason is that by default, the data passed in through the data option, if it is an object (technically speaking, as long as it is not a string), 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 is uploaded successfully, the console will print "{infor:"success"}" information.

This is the end of the front-end part. Let’s look at the code on the Node.js side.

The file structure is as follows:

How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server

Let’s first look at routing - the content in 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"); //路由事件监听 uploadAction.uploadTest.uploadFile(); //文件上传监听 // development only if ('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')); });

and initial There are a few differences in app.js. I exported the app object for reuse in fileUpload.js, then introduced the fileUpload.js module, and obtained the uploadTest object that saves all methods of the module through the interface object and called the uploadFile method. .

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"});return;} i++; } //上传队列文件 function upLoad(index){ var filename = req.files["file"+index].originalFilename || path.basename(req.files["file"+index].path); //path接口可以指定文件的路径和文件名称,"\结尾默认为路径,字符串结尾默认为文件名" var targetPath = path.dirname("") + '/public/uploadFiles/' + filename; //fs创建指定路径的文件并将读取到的文件内容写入 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 it is highly creative, which is what I Reasons to like it. We see that there are actually very few key codes here. Let me briefly introduce the logical process of implementing file upload:

•Get the file name of the uploaded file

•Set the file The storage location, and the file name

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

In order to achieve uploading multiple files, I also do Some matching operations are performed, which are very intuitive and not difficult to understand.

After the file is successfully uploaded, it will appear under the uploadFiles file under the public file.

The modules used in the file are recorded in package.json and can be installed by entering the same-level directory address of package.json and using the command "npm install". If you directly run the project file downloaded from github, there is no need to install it.

The above is the implementation method introduced by the editor to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server. I hope it will be helpful to you. If you have any questions, please Leave me a message and I will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more related articles on the implementation method of combining NodeJS and HTML5 to drag and drop multiple files to upload to the server, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn