Node.js uses express-fileupload middleware to upload files

Node.js uses express-fileupload middleware to upload files

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 project

mkdir 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\" "
  }
}
  • main to server.js
  • start Start express using node
  • The server uses nodemon to start express. Nodemon will monitor whether the server.js file has changed (ctrl+S). If there is a change, restart the server, but node startup will not. You need to restart the service manually (ctrl+C and re-run node server.js after changing the file)
  • client starts the client and then we will create a client folder to write react components
  • dev uses concurrently to start the server and client at the same time

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

  • serviceWorker.js
  • logo.svg
  • index.css // Later we will use the link tag to import bootstrap from cdn
  • App.test.js // Just a small demo

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 Components

We need to write 3 components in total, namely

  • FileUpload.js: Use the form tag's onSubmit and axios to send an upload request
  • Message.js: Displays information about successful upload, server error or no file selected
  • Progress.js: Display 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 (
    <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.js

import 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">&times;</span>
      </button>
    </div>
  )
}
Message.propTypes = {
  msg: PropTypes.string.isRequired,
}
export default Message

Progress.js

import 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:
  • How to manage large file uploads and breakpoint resume based on js
  • JavaScript using Ckeditor + Ckfinder file upload case detailed explanation
  • jQuery implements asynchronous file upload ajaxfileupload.js
  • Backend code example for large file upload based on JavaScript
  • JS can breakpoint resume file upload to achieve code analysis
  • FormData class in JS implements file upload
  • The FileReader class in JS implements the function of timely preview of file upload
  • js to implement file upload style details

<<:  A brief analysis of Linux to check the firewall status and the status of the ports open to the outside world

>>:  Detailed explanation of MySQL user and permission management

Recommend

mysql splits a row of data into multiple rows based on commas

Table of contents Separation effect Command line ...

React realizes secondary linkage effect (staircase effect)

This article shares the specific code of React to...

Based on JavaScript ES new features let and const keywords

Table of contents 1. let keyword 1.1 Basic Usage ...

Solutions for high traffic websites

First: First, confirm whether the server hardware ...

Implementation of MySQL scheduled backup script under Windows

On a Windows server, if you want to back up datab...

Detailed explanation of nginx upstream configuration and function

Configuration Example upstream backend { server b...

Analysis of the principles of docker containers

Table of contents 01 What is the essence of a con...

vue.config.js packaging optimization configuration

The information on Baidu is so diverse that it...

Detailed explanation of the use of Docker commit

Sometimes you need to install certain dependencie...

A detailed introduction to for/of, for/in in JavaScript

Table of contents In JavaScript , there are sever...

Vue implements horizontal scrolling of marquee style text

This article shares the specific code for Vue to ...

WeChat applet implements simple calculator function

WeChat applet: Simple calculator, for your refere...

Detailed explanation of JavaScript state container Redux

Table of contents 1. Why Redux 2. Redux Data flow...

MySQL InnoDB monitoring (system layer, database layer)

MySQL InnoDB monitoring (system layer, database l...