Use ajax + NodeJS to upload images,
The front end sends a request using jquery ajax, and the back end uses the NodeJS multer module to upload images. This demo gives me the feeling that we must be able to implement it on our own, instead of simply "using it" after reading what others have written.
Note)
Create a folder named uploads in the public directory to save the uploaded images.
Install the multer module:
npm i -S multer
Code)
1. app. js
Const express = require ('express '); const multer = require ('multer'); const path = require ('path'); const app = express (); // For all requests, go to the current public directory of the project to find the requested file, and then return to the 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) {res. send ({err: null, // filePath: indicates the path where the image is stored in the project. filePath: 'uploads'/'+ path. basename (req. file. path)}) ;}); app. listen (3000, function () {console. log ("app is listening 3000 port ");});
2.index.html
<! DOCTYPE html>
Here is the demo address.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.