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

How to set a fixed IP address in CentOS7 virtual machine

Since my development environment is to install Ce...

Solve the problem of Docker starting Elasticsearch7.x and reporting an error

Using the Docker run command docker run -d -p 920...

Util module in node.js tutorial example detailed explanation

Table of contents Starting from type judgment Str...

How to use CSS attribute value regular matching selector (tips)

There are three types of attribute value regular ...

Example code for implementing auto-increment sequence in mysql

1. Create a sequence table CREATE TABLE `sequence...

How to insert 10 million records into a MySQL database table in 88 seconds

The database I use is MySQL database version 5.7 ...

Detailed explanation of the usage of the ESCAPE keyword in MySQL

MySQL escape Escape means the original semantics ...

MySQL data table partitioning strategy and advantages and disadvantages analysis

Table of contents Why do we need partitions? Part...

Detailed installation and use tutorial of mysql 8.0.15 under windows

This article shares with you the detailed install...

Detailed explanation of the lock structure in MySQL

Mysql supports 3 types of lock structures Table-l...

Thoughts on truncation of multi-line text with a "show more" button

I just happened to encounter this small requireme...

Swiper.js plugin makes it super easy to implement carousel images

Swiper is a sliding special effects plug-in built...

Detailed tutorial on running multiple Springboot with Docker

Docker runs multiple Springboot First: Port mappi...

Teach you how to use MySQL8 recursive method

I have previously written an article about recurs...