ElementUI method of verifying the size of an image before uploading

Upload component usage of ElementUI

See the official documentation for the properties, here we use before-upload=”beforeAvatarUpload” This hook function, as its name indicates, is a method that executes before an image is uploaded. This is where you can perform some validation.

<template>
  <div class="blog-main-views">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
  </div>
</template>
 methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if(! isJPG) {this.$message.error('Upload profile picture in JPG format only! ');
      }
      if(! isLt2M) {this.$message.error('Upload profile picture size cannot exceed 2MB! ');
      }
      returnisJPG && isLt2M; }}}Copy the code

Here we print out the file argument

You can see that it contains the file name, size, and type, but not the width and height of the image.

To verify the width and height of the image, I use javascript native API FileReader

Javascript native API FileReader

Learn how to use the API first, and then verify it with elementUI

1, FileReader interface method

The FileReader interface has four methods, three to read the file and one to interrupt the reading.

  • ReadAsText: This method takes two arguments, the second of which is the encoding of the text. The default value is UTF-8. This method is very easy to understand. It reads the file as text, and the result is the contents of the text file.

  • ReadAsBinaryString: This method reads the file as a binary string, which we usually pass to the back end, which can store the file from this string.

  • ReadAsDataURL: This method reads a file as a string beginning with data:, which is essentially a data URL. Data URLS are a way to embed small files directly into a document. I’m going to use that method here.

2. FileReader interface event

The FileReader interface includes a complete event model to capture the state of a file when it is read.

3. The FileReader property

Whether the read succeeds or fails, the method does not return the read result, which is stored in the Result property.

4. Use FileReader

The FileReader interface is very simple to use, just create an instance without considering browser compatibility

let reader = new FileReader();
Copy the code

If you’re considering a browser, check it out first

if(window.FileReader) {
    let reader = new FileReader();
}
else {
    alert("Browser does not support change it!!");
}
Copy the code

Implementation validation of ElementUI and FileReader

Since it is to get the width and height of the image, I also use the image to verify, since it is an image, we need to use the readAsDataURL method of FileReader interface,

beforeAvatarUpload(file) {
  let reader = new FileReader();
  reader.onload = function () {
    let txt = this.result;
    let img = document.createElement("img");
    img.src = txt;
    img.onload = function () {
      console.log(img.width);
      console.log(img.height); }}; reader.readAsDataURL(file); }Copy the code

The result we get from readAsDataURL is just enough to assign the img tag as a SRC attribute, and then we can use the simplest img.width and img.height to get the width and height, and then verify it

Take a look at the console print, the code is too long, focus on the red box. It seems that it is ok to get the width and height

Finally, we verify that the onload method of the FileReader interface is asynchronous, so we can’t get the IMG attribute, so we use a Promise

The final verification code is as follows

beforeAvatarUpload(file) {
      let _this = this;
      return new Promise(resolve= > {
        let reader = new FileReader()
        reader.readAsDataURL(file);
        reader.onload = function () {
          resolve(this.result)
        }
      }).then((result) = > {
        document.querySelector("#img").src = result;
        let img = document.querySelector("#img")
        img.onload = function () {
          console.log(img.width)
          console.log(img.height)
          const isWidth = img.width < 500
          const isHeight = img.height < 500
          console.log(isWidth)
          console.log(isHeight)
          if(! isWidth) { _this.$message.error('Upload profile picture width cannot exceed 500! ');
          }
          if(! isHeight) { _this.$message.error('Upload profile picture height cannot exceed 500! ');
          }
          returnisWidth && isHeight; }})}Copy the code

Start with an image that doesn’t fit,

Change to a picture that fits the requirements

Now you can verify the size of your image before uploading it.

After the verification of course is to upload

Upload pictures to Sina Cloud based on Express

Target function: picture upload

Operation process: Click upload button -> Upload picture to server -> Return picture URL

1. Uploads using elementUI in components

<el-upload
      class="avatar-uploader"
      action="http://81.xx.xx.113:3000/blog/uploadArticleImg"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
Copy the code

Action Specifies the interface for uploading images

2. Configure the static resource folder

Only when the static resource folder is configured can the image be accessed by URL. In this case, the static resource folder must be opened before DIST, otherwise the image will not be accessed by HTML

// Open the static resource file
app.use(express.static(path.join(__dirname, "public")));

This is to access all static resource files in the dist directory
app.use(express.static(path.resolve(__dirname, './dist')));
// Because it is a single page application, all requests go to /dist/index.html
app.get(The '*'.function(req, res) {
    const html = fs.readFileSync(path.resolve(__dirname, './dist/index.html'), 'utf-8');
    res.send(html);
})
Copy the code

3. Interface for uploading pictures

The server side uses the Multer module to process the uploaded image, using post mode and adding upload.single(‘file’).

//blog.js

// Image upload module
const multer = require('multer')
// Configure the upload path
const upload = multer({ dest: __dirname + '.. /.. /public/uploads' })
//upload.single() indicates the upload of a single file
blog.post('/uploadArticleImg', upload.single('file'), require("./blog/uploadArticleImg"));
Copy the code

The problem with the multer module is that it changes the uploaded file name to random garbled characters and does not retain the suffix, which results in the front end downloading the file instead of displaying the image. To do this, you need to use the path module to resolve the original file name extension and then use the FS method to add the suffix to the file

//uploadArticleImg.js

// Introduce the path module
const path = require("path");
// Import the fs module
const fs = require("fs");
module.exports = async(req, res) => {
    // Receive file information
    const file = req.file;
    // Get the suffix of the original file name
    const suffix = path.parse(req.file.originalname).ext;
    // The old file name
    const oldname = req.file.path;
    // New file name
    const newname = req.file.path + suffix;
    // Call fs.renamesync () to add the suffix
    fs.renameSync(oldname, newname);
    // Get the URL of the image
    file.url = ` http://81.70.96.113:3000/uploads/${file.filename}` + suffix;
    // Returns file information
    res.send(file);
}
Copy the code

From here, you can upload the image normally and return the URL of the image

4. Upload pictures to Sina Cloud

Accidentally found sina cloud can upload pictures with, the amount of data in a certain range or free, reduce their own not rich server memory pressure.

/* * @author: hanZHIwei * @date: 2020-10-07 00:46:47 * @lasteditTime: 2020-10-13 00:42:41 * @FilePath: \blog\serve\route\blog\uploadArticleImg.js */
// Introduce the path module
const path = require("path");
// Import the fs module
const fs = require("fs");

// Sina SDK references
const sinaCloud = require('scs-sdk');
// Configure accessKey and secretKey of Sina cloud
const config = new sinaCloud.Config({
    accessKeyId: '2wesaabmtYD4N3SwxkfM'.secretAccessKey: 'e75005531b2e364d72efb8ee729f0825629a158a'.sslEnabled: false
});

// Instantiate Sina cloud storage
var myBucket = new sinaCloud.S3({ params: { Bucket: 'duwanyu.com'}});// The current instance is in effect:
myBucket.config = config;


module.exports = async(req, res) => {
    // Receive file information
    const file = req.file;
    // Get the suffix of the original file name
    const suffix = path.parse(req.file.originalname).ext;
    // Old file name (generated by the module)
    const oldname = req.file.path;
    // New file name
    const newname = req.file.path + suffix;

    // Call fs.renamesync () to add the suffix
    fs.renameSync(oldname, newname);
    // Get the URL of the image
    / / file. The url = ` http://81.70.96.113:3000/uploads/${file. The filename} ` + suffix;
    // The original file name (the file name itself)
    const remoteFilename = req.file.originalname;
    // Read the file according to the new file name
    const fileBuffer = fs.readFileSync(newname);

    // Upload the file
    myBucket.putObject({
        ACL: 'public-read'./ / permission
        Bucket: 'duwanyu.com/images'.// Upload to the images folder in duwanyu.com
        Key: remoteFilename, // Upload file name to Sina cloud
        Body: fileBuffer / / file
    }, function(error, response) {
        if (error) {
            res.json("Uploading sina cloud failed");
        } else {
            // Upload the image successfully, return the image address to the front end
            file.sinaPath = "http://sinacloud.net/duwanyu.com/images/" + remoteFilename;
            // Get the URL of the image
            file.url = ` http://81.70.96.113:3000/uploads/${file.filename}` + suffix;
            // Returns file informationres.send(file); }}); }Copy the code

Done, sina cloud at this time we have uploaded the picture!

Make an advertisement

This is my open source favorites url project

Project address 👉👉 Click to enter, you can directly set as the browser home page or desktop shortcut for use, I am using, long-term maintenance.

Completely open source, you can research, secondary development. Of course, you are still welcome to click Star⭐⭐⭐ 👉 ⭐ source link (gitee) Source link (github) source link (Github)

Links to integrate

🔊 Project preview address (GitHub Pages):👉👉alanhzw.github. IO

🔊 Project preview alternate address (own server):👉👉warbler.duwanyu.com

🔊 source code address (gitee):👉👉gitee.com/hzw_0174/wa…

🔊 source address (github):👉👉github.com/alanhzw/War…

🔊 My blog :👉👉www.duwanyu.com