This article uses express as the server and the middleware function provided by the express-fileupload library to accept images from the client and store them as files on the server. The client uses the create-react-app framework, bootstrap UI, and axios to send http requests and provide the current progress value of the progress bar. After the upload is successful, the image is displayed according to its location on the server. Initialize the projectmkdir react-file-upload // Create the project root directory cd react-file-upload npm init -y // Initialize npm and create package.json Install some necessary dependencies npm i express express-fileupload npm i -D nodemon concurrently // You can run the client and server in parallel (test on your local machine) 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\" " } }
Writing the Server Let's write the server.js file const express = require('express'); const fileUpload = require('express-fileupload'); const app = express(); // Use express-fileupload middleware app.use( fileUpload() ); // Process the post request sent by the /upload page app.post('/upload', (req, res) => { // The files property in req is added by express-fileupload middleware!? (Question temporarily saved) // Check if the files attribute exists and if there is a file, return 400 if not. if (req.files === null) { return res.status(400).json({msg:'no file uploaded'}); } // Otherwise get the file // file is defined by the first parameter of formData.append('file', file) in the following text and can be customized to other names const file = req.files.file; // Move the file to the location specified by the first parameter. If there is an error, 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 display the uploaded file according to the path of the file on the server after uploading it // We will then implement this in the react component // Create an uploads folder under the public folder in the client to save the uploaded files res.json({fileName: file.name, filePath: `uploads/${file.name}`}); }); }); app.listen(5000,() => {console.log('Server started...')}); Now run server.js again to ensure there are no errors. You will see Server started in the console... npm run server Initialize the client Then we create the client and initialize the project using the create-react-app scaffolding npx create-react-app client After initialization is completed, we can selectively delete some unnecessary files
We delete the index.css introduced in the src/index.js file, and directly introduce the bootstrap css and js in the index.html template file in the public folder <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" rel="external nofollow" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <!-- Import CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="external nofollow" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" rel="external nofollow" /> <title>React File Uploader</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- Import js --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> Writing ComponentsWe need to write 3 components in total, namely
FileUploadimport React, { useState } from 'react' import axios from 'axios' import Message from './Message' import Progress from './Progress' const FileUpload = () => { return ( <div> {message ? <Message msg={message} /> : null} <form onSubmit={onSubmit}> <div className="custom-file mb-4"> <input type="file" className="custom-file-input" id="customFile" onChange={onChange}></input> <label className="custom-file-label" htmlFor="customFile">{filename}</label> </div> <Progress percentage={uploadedPercentage}></Progress> <input className="btn btn-primary btn-block mt-4" type="submit" value="Upload"></input> </form> { uploadedFile? <div className="row mt-5"> <div className="col-md-6 m-auto"> <h3 className="text-center">{uploadedFile.name}</h3> <img style={{width:'100%'}} src={uploadedFile.filePath} alt=""></img> </div> </div> : <p>nothing uploaded yet...</p> } </div> ) } export default FileUpload Message.jsimport React from 'react' import PropTypes from 'prop-types' const Message = ({msg}) => { console.log('her') return ( <div className="alert alert-info alert-dismissible fade show" role="alert"> {msg} <button type="button" className="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> ) } Message.propTypes = { msg: PropTypes.string.isRequired, } export default Message Progress.jsimport React from 'react' import PropTypes from 'prop-types' const Progress = ({percentage}) => { return ( <div className="progress"> <div className="progress-bar" role="progressbar" style={{ width: `${percentage}%` }} aria-valuenow={percentage} aria-valuemin="0" aria-valuemax="100">{percentage}%</div> </div> ) } Progress.propTypes = { percentage: PropTypes.number.isRequired, } export default Progress test So far, all functional components have been completed. npm run dev Finally, attach the git address Git This is the end of this article about using express-fileupload middleware in node.js to upload files. For more related node.js file upload content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
>>: Detailed explanation of MySQL user and permission management
Table of contents Separation effect Command line ...
This article shares the specific code of React to...
Table of contents 1. let keyword 1.1 Basic Usage ...
There is no problem with the Dockerfile configura...
First: First, confirm whether the server hardware ...
On a Windows server, if you want to back up datab...
Configuration Example upstream backend { server b...
Table of contents 01 What is the essence of a con...
The information on Baidu is so diverse that it...
Sometimes you need to install certain dependencie...
Table of contents In JavaScript , there are sever...
This article shares the specific code for Vue to ...
WeChat applet: Simple calculator, for your refere...
Table of contents 1. Why Redux 2. Redux Data flow...
MySQL InnoDB monitoring (system layer, database l...