Use express + multer to implement the image upload function in node.
The following describes how to use express + multer to upload images in node. The specific content is as follows:
In the front-end, we use ajax to asynchronously upload images, use file-input to upload images, use formdata objects to process image data, and post images to servers.
Use multer middleware in node to process the upload routing Interface
Multer document
Package. json
Html section
<Body> <div class = "form-group"> <label> File input: </label> <input type = "file" name = "file" id = "file"> <p id = "result"> </p> </div> <button id =" upload "class =" btn-default "> submit </button> </body>
Js Section
<Script src = "https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"> </script> <script> // function of the business logic for uploading images uploadFile () {// input var file = document for uploading images. getElementById ("file") // The image content is large because it is submitted by post, so we chose to use formdata to carry data // create the formdata object var formData = new FormData (); // put data (key-Value Pair method) formdata into the formData object. append ('file', file. files [0]); // submit the request $. ajax ({url: '/upload', // Request Path type: 'post', data: formDa Ta, contentType: false, // to allow the browser to determine contentType processData: false Based on the passed formdata, // same as success: function (data) {if (200 = data. code) {upload ('{result'}.html ("uploaded successfully! "); $ ('# Img'). attr ('src', data. data);} else {failed ('{result'}.html (" Upload Failed! ");} Console. log (2)}, error: function () {$ ("# result" ..html ("communication error with server") ;}}); console. log (1)} // Add to button click event function postPage () {// upload button var uploada = document. getElementById ('upload'); uploada. addEventListener ("click", function () {uploadFile () ;}, false);} window. onload = function () {postPage () ;}</script>
NodeJS logic code
Const http = require ('http') const path = require ('path') const express = require ('express ') // is the middleware for processing the multipart/form-data format (mainly used in the upload function) in nodejs // documentation: https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.mdconst multer = require ('multer ') const app = express () // configure the static directory app of express. use (express. static (path. join (_ dirname, 'public'); app. get ('/', (req, res) => {res. sendFile (_ dirname + '/index.html ')}) // Configure diskStorage to control the file storage location and file name. var storage = multer. diskStorage ({// determine the image storage location destination: function (req, file, cb) {cb (null ,'. /public/uploadImgs ')},! [] (Http://images2017.cnblogs.com/blog/1283058/201802/1283058-20180201154342296-515041615.png) // determine the name of the image stored, note that if you use the original name, it may cause a conflict of filename: function (req, file, cb) {cb (null, Date. now () + file. originalname)}); // a generated Tool for processing uploads. You can Input storage, limits, and other configuration var upload = multer ({storage: storage }); // The app that receives the Image Upload request. post ('/upload', upload. single ('file'), function (req, res, next) {// The image has been put into the server, and the req has been processed by the upload middleware (with file and other information added) // The absolute address of the image in the server. var url = '/uploadImgs/' + req. file. filename res. json ({code: 200, data: url}); http. createServer (app ). listen (3000, () => {console. log ('server is listening ')})
I feel good about myself. I don't know why I want to remove my homepage from my blog ....
Next time, if (delete) {alert ('never publish anything again. ')} else {alert (1 )}
Summary
The above section describes how to use express + multer to upload images in node. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!