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:401816browse

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:

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(&#39;express&#39;);
var routes = require(&#39;./routes&#39;);
var user = require(&#39;./routes/user&#39;);
var http = require(&#39;http&#39;);
var path = require(&#39;path&#39;);
var app = express();
// all environments
app.set(&#39;port&#39;, process.env.PORT || 3000);
app.set(&#39;view engine&#39;, &#39;jade&#39;);
app.use(express.favicon());
app.use(express.logger(&#39;dev&#39;));
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 (&#39;development&#39; == app.get(&#39;env&#39;)) {
app.use(express.errorHandler());
}
app.get(&#39;/users&#39;, user.list);
http.createServer(app).listen(app.get(&#39;port&#39;), function(){
console.log(&#39;Express server listening on port &#39; + app.get(&#39;port&#39;));
});

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(&#39;connect-multiparty&#39;);
var App=require("../app");
var path = require(&#39;path&#39;);
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("") + &#39;/public/uploadFiles/&#39; + 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