1. Build express projects

express -e nodejs-uploadfile
Copy the code

2. Download the Multer middleware

npm i multer or yarn multer
Copy the code

3. Reference multer in routes/index.js. Because file operation needs to be used, reference fs module and specify file upload directory

const multer  = require('multer');
const fs = require('fs');

const UPLOAD_PATH = './uploads'
Copy the code

Single file upload: the file in index. HTML is as follows (the form file must be encType =”multipart/form-data”).

<form action="/upload" method="post" enctype="multipart/form-data">
    <input name="fileUpload" type="file" />
    <img src="" alt="">
    <button type="submit"</button> </form>Copy the code

Add an upload route to routes/index.js to handle file uploads

router.post('/upload', upload.single('fileUpload'), function (req, res, next) {
  const { file } = req;
  fs.readFile(file.path, function(err, data) {
    fs.writeFile(`${UPLOAD_PATH}/${file.originalname}`, data, function (err) {
      if (err) res.json({ err })
      res.json({
        msg: 'Upload successful'}); }); })})Copy the code

If the uploaded file is an image, you can also preview the image using the FileReader object

(function($){
  $('input').on('change'.function(event) {
    var files = event.target.files,
        reader = new FileReader();
    if(files && files[0]){
        reader.onload = function (ev) {
            $('img').attr('src', ev.target.result);
        }
        reader.readAsDataURL(files[0]);
    }
  })
}(jQuery))
Copy the code

Multi-file upload: The principle of multi-file upload is the same as that of single-file upload. The code is as follows:

router.post('/upload', upload.array('fileUpload'), function (req, res, next) {
  const files  = req.files;
  const response = [];
  const result = new Promise((resolve, reject) => {
    files.map((v) => {
      fs.readFile(v.path, function(err, data) {
        fs.writeFile(`${UPLOAD_PATH}/${v.originalname}`, data, function(err, data) {
          const result = {
            file: v,
          }
          if (err)  reject(err);
          resolve('success');
        })
      })
    })
  })
  result.then(r => {
    res.json({
      msg: 'Upload successful',
    })
  }).catch(err => {
    res.json({ err })
  });
})
Copy the code

The code is available at github.com/bWhirring/n…