Home>

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/.

Unzip the downloaded zip format package. It is recommended to run the project with webstom.Launch the project via app.js,If prompted to find the node.exe execution environment,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.

Look at the code here:

<! 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>drag and drop here</div>
<div></div>
<script>
var a1=document.getelementbyid ("a1");
function handleevent (event) {
var info="",output=document.getelementbyid ("out-input"),files, i, len;
eventutil.preventdefault (event);//Prevent the default behavior of 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, //Specify the default read string operation for uploaded data
success:function (rs) {
console.log (rs);
},error:function (r) {
alert ("File upload error!");
}
});
}
}
eventutil.addhandler (a1, "dragenter", handleevent);
eventutil.addhandler (a1, "dragover", handleevent);
eventutil.addhandler (a1, "drop", handleevent);
</script>
</body>
</html>

HTML content is simple,One shows the allowed drag range,A div block that displays the content of the uploaded file.

js part:

Here I prepared an eventutil interface object,You can also think of it as a small library for handling events,Its role is to encapsulate different methods of the same event bound to each browser,In order to implement the event binding method common to each browser,Uniformly implemented with eventutil objects,You can simply look at its implementation code,very simple.

When the browser detects the three events of dragging,"Dragenter", "dragover", "drag" default behavior is blocked,Execute our custom event when it is a "drag" case.

Because we uploaded files,So an instance of formdata is used here, and a file is added to the object through append () to become a queue file.After uploading to the server, it will be parsed into attribute objects in the queue order.In the event, use "event.datatransfer.files" to get the files stored in the event.

One thing to note here is that the ajax method of jquery needs to configure processdata to false when uploading a file object, which means that it does not use the default read string operation.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), it will be processed and converted into a query string.To match the default content type "application/x-www-form-urlencoded". If i want to send dom tree information or other information that you do not want to convert,Need to be set to false.

The console will print "{infor:" success "}" after the file is uploaded successfully.

At this point, the front end is over,Let's look at the code on the node.js side.

The file structure is as follows:

Let's first look at the contents of 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");
//Routing event monitoring
uploadaction.uploadtest.uploadfile ();
//File upload monitoring
//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"));
});

There are several differences from the original app.js,I exported the app object for reuse in fileupload.js,Then the fileupload.js module is introduced, and the uploadtest object that holds all the methods of the module is obtained through the interface object and the uploadfile method is called.

OK, finally we 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 the 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 file path and file name,"\ Ends with path by default,End of string defaults to file name "
var targetpath=path.dirname ("") + "/public/uploadfiles /" + filename;
//fs creates a file with the specified path and writes the content of the read file
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 is highly invasive,That's why I like it.We see that the key code here is actually very small,I briefly introduce the logical process of file upload:

•Get the file name of the uploaded file

•Set the storage location of the file,And file name

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

In order to upload multiple files,I also did some matching operations,It is intuitive and not difficult to understand.

After the file is successfully uploaded,Will appear under the uploadfiles file under the public file.

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

  • Previous Ajax for remote communication
  • Next IOS native QR code scanning