In the code

Elementui code

<div id="elemenui_upload">
  <el-upload
    action="/localServer/users/upload"
    ref="upload"
    :auto-upload="false"
    multiple
    :limit="5"
    :on-success="successUp"
  >
    <el-button slot="trigger" size="small" type="primary">Choose picture</el-button>
    <el-button size="small" type="success" @click="Onsubmit">Uploading to the Server</el-button>
    <div slot="tip" class="el-upload__tip">
      jpg/png files with a size less than 500kb
    </div>
  </el-upload>
</div>
Copy the code

The action attribute in the

tag is set to the address of the expres server route, ref is set to upload, on-success is the file upload success event, trigger event, execute successUp function

The second

is the submit button, and click to execute the Onsubmit function

IView code

<div id="ivew_upload">
  <Upload action="/localServer/users/upload" :on-success="successUp">
    <Button icon="ios-cloud-upload-outline">To upload pictures</Button>
  </Upload>
</div>
Copy the code

The code of iView is relatively simple. When the button of uploading a picture is clicked, submit will be automatically executed without us setting another function.

The iView triggers the on-success event and executes the same function as Elementui

Method declarations for the above code

export default {
  methods: {
    Onsubmit() {
      this.$refs.upload.submit();
    },
    successUp(response, file, fileList) {
      console.log("Through 127.0.0.1:7882 \ \" + response.file.path + "View pictures"); ,}}};Copy the code

this.$refs.upload.submit(); It means to find the component whose ref is upload and execute the submit function to upload the picture to the server

SuccessUp takes three arguments: Response is the response returned by the server, file is the current file object, and fileList is the list of current files

The figure above shows the data returned by Response. Path indicates the location of the image on the server. Originalname indicates the originalname of the image on the host before uploading

The back-end code

const express = require('express');
const router = express.Router();
const multer = require("multer");
const fs = require('fs');
const path = require('path');
var upload = multer({
  storage: multer.diskStorage({
    // Set the file storage location
    destination: function (req, file, cb) {
      let date = new Date(a);let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2.'0');
      let day = date.getDate().toString().padStart(2.'0');
      let dir = "./uploads/" + year + month + day;

      // Check whether the directory exists and create it if it does not
      if(! fs.existsSync(dir)) { fs.mkdirSync(dir, {recursive: true
        });
      }

      //dir is the directory where the image uploaded successfully to the server is stored
      cb(null, dir);
    },
    // Set the file name
    filename: function (req, file, cb) {
      let fileName = Date.now() + path.extname(file.originalname);
      //fileName is the name of the uploaded file
      cb(null, fileName); }})}); router.post('/upload', upload.single('file'), (req, res) = > {
  console.log(req.file);
  res.json({
    file: req.file
  })
})
module.exports = router;
Copy the code

Use the multer module. If not, download NPM install multer-s

If the image is successfully uploaded to the server, a folder uploads will be created in the SRC directory. Under this folder, a sub-folder named year month date when the image is successfully uploaded will be created

Res. json is basically the same as res.send, except that res.json returns in JSON format

Pay attention to

When setting the file name at the back end, it is best not to use other characters to avoid static access failure.

Do not set other characters, including _ (_), when setting the route on the backend.

When configuring the proxy in vue.config.js, the customized proxy name should not contain other characters and use the camel name as far as possible.

Static access to images via Express

Use (‘/uploads’, express.static(‘uploads’)) in app.js file to view the image by accessing 127.0.0.1: Express port /uploads/ photo upload date/photo name