Ajax + NodeJS implementation picture upload instance

The front desk uses jQuery’s AJAX request, and the background is uploaded with the NodeJS Multer module. This demo gives me a sense to be able to achieve it, not to read others, I will “bid”

ajax +NodeJS 实现图片上传实例

Note (Note)

Everyone first creates a folder called UPLOADS in the public directory, this folder is used to save the picture you uploaded


Install MULTER Module:


NPM I -S MULTER
   
Code (code)

Const express = Require (‘express’); const multer = required (‘MULTER’); const path = request (‘PATH’); const App = Express (); // All requests come over, go to the current public directory to find the requested file, then return to app.use (express.static (‘./ public’) ); // Select DiskStorage Storage const storage = multer.diskStorage ({Destination: Function (REQ, File, CB) {CB (Null, Path.Resolve (‘public / uploads’));}, filename: function (Req, File, cb) {CB (Null, Date.Now () + Path.extName (file.oriGinaLName)); // Added the file extension}}}; const upload = MULTER ({Storage: Storage}); app.post (‘/ profile’, Upload.single (‘Avatar’), Function (Req, RES, NEXT) {R.Snd ({Err: null, // filepath: is a picture in the project in the project filepath: ‘uploads /’ + path.basename (req.path)};}; app .Listen (3000, Function () {Console.log (“App IS Listening 3000 Port”);});

2.index.html
   
Title

    Upload    Function Handle () {// Get uploaded File objects, here is a picture object let file = document.getlementByid ("choose"). Files [0]; Let formdata = new formData (); FormData.Append ("Avatar", file); // Set key to avartar, value for the file object $. .ajax ({type: 'post', url: '/ profile ",Data: Formdata, ProcessData: False, Success: Function ("src", data.filepath; // Upload success, image display}, error: function (err) { Console.log (Err.Message);}}}}     DEMO address is here  , the above is this article All of the content, I hope to help everyone's learning, I hope everyone will support Tumi Clouds.                      
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment