As a node beginner, recently in a chat software, support registration, login, online single, multi-person chat, expression send, all kinds of file upload download, delete friends, chat record save, notify sound switch, background image switch, game and other functions, so used the Multer module, after various search documents, Do demo example, finally successfully achieve a single file upload function, support the majority of file format upload, at the same time display to the Web page, this article mainly introduces the Ajax with node JS multer implementation File Upload function, the need for friends can refer to, hope to help everyone.
Effect
is not a kind of visual sense, yes, is based on the web version to do,
To achieve the overall effect, to cooperate with CSS and HTML to do, front-end beginners, the first blog, really catch the urgency, the recent, will put the code on GitHub up, interested friends can go to see
Below directly on the code, lightly abused
Configuration
Installation
Install Multer directly from the cmd command window
NPM Install Multer-save
Server code
Introduce Httpconst http=require ("http"),//Introduce Expressconst Express=require ("Express");//Introduce Multerconst Multer=require (" Multer ");//create server, bind listening port var app=express (); var server=http.createserver (APP); Server.listen (8081);//Build public folder, Put the HTML file into it, allow access to App.use (express.static ("public"));//File Upload required code//set File upload path and file name var storage = Multer.diskstorage ({ destination:function (req, file, CB) { //file uploaded successfully will be placed under public upload folder CB (NULL, './public/upload ') } , filename:function (req, file, CB) { //settings file name is its original name, you can also add other characters to distinguish the same file, such as File.originalname+new Date (). GetTime (); Use time to differentiate CB (NULL, file.originalname) }); var upload = Multer ({ storage:storage});// Handles AJAX requests from the page. Single File Upload app.post ('/upload ', upload.single (' file '), function (req, res, next) { ///splicing file after uploading the network path, var url = ' http://' + req.headers.host + '/upload/' + req.file.originalname; Send it back to client Res.json ({ code:1, data:url }); Res.end ();});
Client code
<! DOCTYPE html>