Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use express-fileupload Middleware to upload Files in node.js

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how node.js uses express-fileupload middleware to upload files". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

This paper uses express as the server, uses the middleware function provided by the express-fileupload library to accept the pictures from the client, and stores the pictures as files on the server. The client uses the create-react-app framework, and bootstrap UI,axios sends a http request and provides the current progress value of the progress bar. After a successful upload, the image is displayed according to the location of the image on the server.

Initialize the project

Mkdir react-file-upload / / create project root directory cd react-file-uploadnpm init-y / / initialize npm create package.json

Install some necessary dependencies (dependencies)

Npm i express express-fileuploadnpm I-D nodemon concurrently / / can run both client and server in parallel (testing locally)

Change the scripts script in react-file-upload/package.json

{"main": "server.js", "script": {"start": "node server.js", "server": "nodemon server.js", "client": "npm start-- prefix client", "dev": "concurrently" npm run server "" npm run client ""}}

Change main to server.js

Start uses node to start express

Server uses nodemon to start express, and nodemon monitors server.js files for changes (ctrl+S). If there are any changes, restart the server but not node. You need to restart the service manually (ctrl+C and rerun node server.js after changing the file)

Client starts the client and then we create a client folder to write the react component

Dev uses concurrently to start both the server and the client

Write a server

Let's write the server.js file

Const express = require ("express"); const fileUpload = require ("express-fileupload"); const app = express (); / using express-fileupload middleware app.use (fileUpload ()); / / processing post request app.post sent by / upload page ("/ upload", (req, res) = > {/ / req is added by express-fileupload middleware!? (question hold) / / determine whether the files attribute exists and whether a file has been sent. If no 400 if (req.files = null) {return res.status (400) .json ({msg: "no file uploaded"}) is returned;} / otherwise get the file / / file can be customized to another name const file = req.files.file by the first parameter definition of formData.append ("file", file) later. / / move the file to the location specified by the first parameter and return 500 file.mv (`${_ dirname} / client/public/uploads/$ {file.name}`, err = > {if (err) {console.error (err); return res.status (500) .send (err)) } / / if there is no error, return a json / / We plan to upload the file and display the uploaded file according to the path of the file on the server / / then we will implement / / create a uploads folder under the public folder in the client to save the uploaded file res.json ({fileName: file.name, filePath: `uploads/$ {file.name} `}). );}); app.listen (5000, () = > {console.log ("Server started...")})

Now run server.js again to make sure there are no errors and you will see Server started... on the console

Npm run server

Initialize the client

Then we create the client and we initialize the project using create-react-app scaffolding

Npx create-react-app client

After initialization, we can selectively delete some unnecessary files.

ServiceWorker.js

Logo.svg

After index.css / /, we will introduce bootstrap from cdn with the link tag.

App.test.js / / just a little demo

We delete the index.css introduced in the src / index.js file, and directly introduce bootstrap's css and js into the index.html template file in the public folder.

React File Uploader You need to enable JavaScript to run this app. Write components

We need to write a total of 3 components, which are

FileUpload.js: send upload requests using onSubmit and axios of form tags

Message.js: displays information uploaded successfully, server error or no file selected

Progress.js: display the upload progress bar with axios's onUploadProgress and bootstrap

FileUpload

Import React, {useState} from "react" import axios from "axios" import Message from ". / Message" import Progress from ". / Progress" const FileUpload = () = > {return ({message?: null} {filename} {uploadedFile? {uploadedFile.name})

:

Nothing uploaded yet...

})} export default FileUploadMessage.js

Import React from "react" import PropTypes from "prop-types" const Message = ({msg}) = > {console.log ("her") return ({msg} ×)} Message.propTypes = {msg: PropTypes.string.isRequired,} export default MessageProgress.js

Import React from "react" import PropTypes from "prop-types" const Progress = ({percentage}) = > {return ({percentage}%)} Progress.propTypes = {percentage: PropTypes.number.isRequired,} export default Progress Test

So far, all the functional components have been completed.

Npm run dev

This is the end of the content of "how node.js uses express-fileupload middleware to upload files". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report