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

The magic of tbody tag speeds up the display of table content

You must have saved other people’s web pages and l...

Detailed tutorial on installing centos8 on VMware

CentOS official website address https://www.cento...

Detailed Introduction to Nginx Installation and Configuration Rules

Table of contents 1. Installation and operation o...

Summary of English names of Chinese fonts

When using the font-family property in CSS to ref...

Analysis of the method of setting up scheduled tasks in mysql

This article uses an example to describe how to s...

Tutorial on installing mysql5.7.17 via yum on redhat7

The RHEL/CentOS series of Linux operating systems...

Small problem with the spacing between label and input in Google Browser

Code first, then text Copy code The code is as fol...

Understanding the Lazy Loading Attribute Pattern in JavaScript

Traditionally, developers create properties in Ja...

How to encapsulate timer components in Vue3

background When you open the product details on s...

How to automatically back up the mysql database regularly

We all know that data is priceless. If we don’t b...

MySQL master-slave replication configuration process

Main library configuration 1. Configure mysql vim...

7 interesting ways to achieve hidden elements in CSS

Preface The similarities and differences between ...

Four ways to modify the default CSS style of element-ui components in Vue

Table of contents Preface 1. Use global unified o...

Analysis of MySQL crash recovery based on Redo Log and Undo Log

Table of contents MySQL crash recovery process 1....