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

Analyzing ab performance test results under Apache

I have always used Loadrunner to do performance t...

Several ways to update batches in MySQL

Typically, we use the following SQL statement to ...

Implementing timed page refresh or redirect based on meta

Use meta to implement timed refresh or jump of th...

How to use vite to build vue3 application

1. Installation Tip: There is currently no offici...

Vue3 AST parser-source code analysis

Table of contents 1. Generate AST abstract syntax...

DOCTYPE type detailed introduction

<br />We usually declare DOCTYPE in HTML in ...

Analysis of the advantages of path.join() in Node.js

You might be wondering why you should use the pat...

Simple steps to implement H5 WeChat public account authorization

Preface Yesterday, there was a project that requi...

CSS3 clear float method example

1. Purpose Through this article, everyone can und...

Continuous delivery using Jenkins and Docker under Docker

1. What is Continuous Delivery The software produ...

MYSQL performance analyzer EXPLAIN usage example analysis

This article uses an example to illustrate the us...

In-depth analysis of Linux NFS mechanism through cases

Continuing from the previous article, we will cre...

How to use the Clipboard API in JS

Table of contents 1. Document.execCommand() metho...