Vue uses OSS to upload pictures or attachments

Vue uses OSS to upload pictures or attachments

Use OSS to upload pictures or attachments in vue project

There is no distinction here between uploading pictures and attachments; the upload process is the same;

1. Create a new oss.js file and encapsulate and use oss (need to install the ali-oss package)

const OSS = require('ali-oss')

const OSSConfig = {
  uploadHost: 'http://xxxxx.oss-cn-shenzhen.aliyuncs.com', //OSS upload addressossParams: {
    region: 'oss-cn-shenzhen',
    success_action_status: '200', // default is 200
    accessKeyId: 'LTxxxxxxxxxxxxxxxvnkD',
    accessKeySecret: 'J6xxxxxxxxxxxxxxxxiuv',
    bucket: 'xxxxxxxx-czx',
  },
}

function random_string(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

function uploadOSS(file) {
  return new Promise(async (resolve, reject) => {
    const fileName = `${random_string(6)}_${file.name}`
    let client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket,
    })
    const res = await client.multipartUpload(fileName, file)
    // resolve(res)
    // Or return as follows:
    resolve({
        fileUrl: `${OSSConfig.uploadHost}/${fileName}`,
        fileName: file.name
    })
  })
}

export { uploadOSS }

2. Use oss.js in the page

This is a secondary encapsulation of the elementUI upload component. The component action is not used to upload pictures and attachments, but the OSS upload method is used.

<template>
  <div class="upload-file">
    <el-upload
      ref="fileUpload"
      action=""
      :headers="uploadProps.headers"
      list-type="picture-card"
      :show-file-list="false"
      :http-request="fnUploadRequest"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="handleUpload"
    >
      <slot></slot>
    </el-upload>
  </div>
</template>

<script>
import { getAccessToken, getRefreshToken, getAccessTokenTTL } from "@/utils/auth";
import { uploadOSS } from '@/utils/oss';

export default {
  name: "index",
  data() {
    return {};
  },
  computed: {
    userAccountID() {
      return this.$store.state.user.userAccountID;
    },
    uploadProps() {
      return {
        // action: `${process.env.VUE_APP_BASE_API}/api/file/upload`,
        headers: {
          // The interface may require a token: "",
          Authorization: getAccessToken(),
        },
        data: {},
      };
    },
  },
  methods: {
    handleExceed(file, fileList){
      // console.log(file, fileList);
      this.$message.error('Upload failed, limit the upload quantity to 10 files!');
    },
    handleUpload(file, fileList){
      // console.log(file, fileList);
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'docx' || testmsg === 'doc'
        || testmsg === 'pdf' || testmsg === 'zip' || testmsg === 'rar' || testmsg === 'ppt' || testmsg === 'txt'

      const isLimit10M = file.size / 1024 / 1024 < 10
      var bool = false;
      if(extension && isLimit10M){
        bool = true;
      } else {
        bool = false;
      }
      if(!extension) {
        this.$message.error('Please select the attachment file type!');
        return bool;
      }
      if(!isLimit10M) {
        this.$message.error('Upload failed, cannot exceed 10M!');
        return bool;
      }
      return bool;
    },
    handleSuccess(res) {
      // console.log(res);
      if (res) {
        this.$emit('fileData', res)
        this.$message.success("Attachment uploaded successfully!");
      }
    },
    handleError(err){
      this.$message.error('Failed to upload attachment!');
    },
    // Upload image async fnUploadRequest(options) {
      try {
        // console.log(options);
        let file = options.file; // Get file
        let res = await uploadOSS(file)
        console.log(res);
        //Return data this.$emit("fileData", res);
        this.$message.success("Attachment uploaded successfully!");
      } catch (e) {
        this.$message.error('Failed to upload attachment!');
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-upload,
.el-upload--picture-card {
  // width: 50px;
  height: 0px;
  border: none;
  line-height: 0;
  display: block;
  background: #f5f6fb;
}
.el-upload {
  width: 50px;
}
.img-cont {
  width: 50px;
  height: 24px;
  background: #f5f6fb;
  .img-icon {
    color: #ccc;
  }
  .img-text {
    font-size: 12px;
    height: 24px;
    color: #000;
  }
}
</style>

Use the encapsulated upload component

  	<div class="task-detail pr">
        <el-form-item label="Reason for reporting" prop="taskDesc" required>
          <div class="flex-center upload-position">
            <ImgUpload @imgData="imgData" />
            <FileUpload class="ml10" @fileData="fileData" />
          </div>
          <el-input
            type="textarea"
            v-model="ruleForm.taskDesc"
            placeholder="Please enter the reason for reporting"
            maxlength="200"
            @input="checkiptTaskDesc()"
          ></el-input>
          <div class="ipt-taskDesc-length">{{checkIptTaskDescLen}}/200</div>
          <div class="img-list mt10 flex">
            <ImgZoomIn :imagesList="imagesList" @deleteImg="deleteImg"></ImgZoomIn>
          </div>
          <div class="dotted-line" v-if="imagesList.length > 0 && filesList.length > 0"></div>
          <div class="file-item">
            <HandleFile :filesList="filesList" @deleteFile="deleteFile"></HandleFile>
          </div>
        </el-form-item>
      </div>

insert image description here

The effect is as follows

insert image description here

This is the end of this article about how vue uses OSS to upload pictures or attachments. For more relevant content about how vue uses OSS to upload pictures or attachments, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue+element+oss realizes front-end fragment upload and breakpoint resume
  • Vue Element UI + OSS to realize the function of uploading files
  • Example of how to upload images to Alibaba Cloud OSS storage with Vue.js
  • Example of how to upload pictures to OSS in Vue (pictures have deletion function)
  • Example of using Ali OSS upload function in Vue page (Part 2)
  • Example of using Ali OSS upload function in Vue page (I)

<<:  Detailed explanation of MySQL combined index method

>>:  Steps to purchase a cloud server and install the Pagoda Panel on Alibaba Cloud

Recommend

Vue+js realizes video fade-in and fade-out effect

Vue+js realizes the fade in and fade out of the v...

Nginx implements dynamic and static separation example explanation

In order to speed up the parsing of the website, ...

Record a troubleshooting record of high CPU usage of Tomcat process

This article mainly records a tomcat process, and...

Django+mysql configuration and simple operation database example code

Step 1: Download the mysql driver cmd enters the ...

vue2.x configuration from vue.config.js to project optimization

Table of contents Preface vue.config.js configura...

Web Standard Application: Redesign of Tencent QQ Home Page

Tencent QQ’s homepage has been redesigned, and Web...

Analysis of the difference between Mysql InnoDB and MyISAM

MySQL supports many types of tables (i.e. storage...

Explanation of the new feature of Hadoop 2.X, the recycle bin function

By turning on the Recycle Bin function, you can r...

Pure CSS meteor shower background sample code

GitHub address, you can star it if you like it Pl...

Detailed explanation of the use of stat function and stat command in Linux

stat function and stat command Explanation of [in...

How to use partitioning to optimize MySQL data processing for billions of data

When MySQL queries tens of millions of data, most...

MySQL installation and configuration tutorial for Mac

This article shares the MySQL installation tutori...

Several implementation methods of the tab bar (recommended)

Tabs: Category + Description Tag bar: Category =&...

3 different ways to clear the option options in the select tag

Method 1 Copy code The code is as follows: documen...