


How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server
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:
<!DOCTYPE html> <html> <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">拖拽到此</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); //阻止事件的默认行为 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, //此处指定对上传数据不做默认的读取字符串的操作 success:function(rs){ console.log(rs); }, error:function(r){ alert("文件上传出错!"); } }); } } EventUtil.addHandler(a1, "dragenter", handleEvent); EventUtil.addHandler(a1, "dragover", handleEvent); EventUtil.addHandler(a1, "drop", handleEvent); </script> </body> </html>
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo
