Vue+element+oss realizes front-end fragment upload and breakpoint resume

Vue+element+oss realizes front-end fragment upload and breakpoint resume

Pure front-end implementation:切片上傳斷點續傳.斷點續傳needs to be implemented on the basis of cutting and uploading

The front end previously uploaded OSS without the need for the back end to provide an interface. First, post the complete code, copy it directly, and modify the parameters in new OSS to the relevant information of your company's OSS. If you encounter any problems, please continue reading below.

oss官方文檔

https://help.aliyun.com/document_detail/111268.html?spm=a2c4g.11186623.6.1111.5a583a07LknRUO

The code allows the required environment: vue + element + ali-oss

Install ali-oss: cnpm install ali-oss

Code Implementation

<template>
 <div class="dashboard-editor-container">
 <el-upload
  class="upload-demo"
  action=""
  ref="upload"
  :file-list="fileList"
  :limit="2"
  :on-change="handleChange"
  :on-remove="handleRemove"
  :auto-upload="false"
  accept=""
 >
  <el-button slot="trigger" size="small" type="primary">Select file</el-button>
  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitForm">Upload to server</el-button>
  <el-button style="margin-left: 10px;" size="small" type="success" @click="resumeUpload">Continue</el-button>
  <el-button style="margin-left: 10px;" size="small" type="success" @click="stopUplosd">Pause</el-button>
  <el-button style="margin-left: 10px;" size="small" type="success" @click="abortMultipartUpload">Clear slice</el-button>
 </el-upload>
 <el-progress :percentage="percentage" :status="uploadStatus"></el-progress>
 </div>
</template>

<script>
 let OSS = require('ali-oss') // Import ali-oss plugin const client = new OSS({
 region: 'oss-cn-shanghai', //Fill in the value based on your bucket location accessKeyId: 'LTA*********RaXY', //AccessKeyId of your account
 accessKeySecret: 'uu1************GiS', //accessKeySecret of your own account
 bucket: 'a******o', //bucket name});
export default {
 data () {
 return {
  fileList:[],
  file: null,
  tempCheckpoint: null, // used to cache the current slice content uploadId: '',
  uploadStatus: null, // Progress bar upload status percentage: 0, // Progress bar percentage uploadName: '', // Full path of the bucket where the object is located}
 },
 mounted() {
 // window.addEventListener('online', this.resumeUpload);
 },
 methods: {
 // Click to upload to the server submitForm(file) {
  this.multipartUpload();
 },
 // Cancel the multipart upload event async abortMultipartUpload() {
  window.removeEventListener('online', this.resumeUpload)
  const name = this.uploadName; // The full path of the Bucket where the Object is located.
  const uploadId = this.upload; // Upload uploadId in multiple parts.
  const result = await client.abortMultipartUpload(name, uploadId);
  console.log(result, '=======Clear slice====');
 },
 // Pause multi-part upload.
 stopUplosd () {
  window.removeEventListener('online', this.resumeUpload) // Clear event listener when paused let result = client.cancel();
  console.log(result, '----------- Pause uploading -----------')
 },
 // Slice upload async multipartUpload () {
  if (!this.file) {
  this.$message.error('Please select a file')
  return
  }
  this.uploadStatus = null
  // console.log("this.uploadStatus",this.file, this.uploadStatus);

  this.percentage = 0
  try {
  //object-name can be customized as a file name (such as file.txt) or a directory (such as abc/test/file.txt) to upload the file to the current bucket or a specified directory under the bucket.
  let result = await client.multipartUpload(this.file.name, this.file, {
   headers: {
   'Content-Disposition': 'inline',
   'Content-Type': this.file.type //Note: Set according to the suffix of the image or file. I used '.png' images in my experiment. The specific reasons are explained below},
   progress: (p, checkpoint) => {
   this.tempCheckpoint = checkpoint;
   this.upload = checkpoint.uploadId
   this.uploadName = checkpoint.name
   this.percentage = p * 100
   // console.log(p, checkpoint, this.percentage, '---------uploadId-----------')
   // Breakpoint recording point. You cannot continue uploading directly after the browser is restarted. You need to trigger the upload operation manually.
   },
   meta: { year: 2020, people: 'dev' },
   mime: this.file.type
  });
  console.log(result, this.percentage, 'result= Slice upload completed=');
  } catch (e) {
  window.addEventListener('online', this.resumeUpload) // This listener is placed in the exception handling of disconnected network // Capture timeout exception.
  if (e.code === 'ConnectionTimeoutError') { // Request timeout exception handling this.uploadStatus = 'exception'
   console.log("TimeoutError");
   // do ConnectionTimeoutError operation
  }
  // console.log(e)
  }
 },
 // Resume uploading.
 async resumeUpload () {
  window.removeEventListener('online', this.resumeUpload)
  if (!this.tempCheckpoint) {
  this.$message.error('Please upload first')
  return
  }
  this.uploadStatus = null
  try {
  let result = await client.multipartUpload(this.file.name, this.file, {
   headers: {
   'Content-Disposition': 'inline',
   'Content-Type': this.file.type //Note: Set according to the suffix of the image or file. I used '.png' images in my experiment. The specific reasons are explained below},

   progress: (p, checkpoint) => {
   this.percentage = p * 100
   console.log(p, checkpoint, 'checkpoint----Restore uploaded slice information-------')
   this.tempCheckpoint = checkpoint;
   },
   checkpoint: this.tempCheckpoint,
   meta: { year: 2020, people: 'dev' },
   mime: this.file.type
  })
  console.log(result, 'result-=-=-Resume upload completed')
  } catch (e) {
  console.log(e, 'e-=-=-');
  }
 },

 // Select the file to change handleChange(file, fileList) {
  this.fileList = fileList.filter(row => row.uid == file.uid)
  this.file = file.raw
  //Upload when the file changes // this.submitForm(file)
 },
 handleRemove(file, fileList) {
  this.percentage = 0 //Set the progress bar to zero this.fileList = []
 },
 }
}
</script>

<style scoped>
</style>

If the relevant dependencies have been installed, but there is still an error when operating the above code, please check the following issues

 const client = new OSS({
 region: 'oss-cn-shanghai', //Fill in the value based on your bucket location accessKeyId: 'LT******XY', //AccessKeyId of your account
 accessKeySecret: 'uu*********GiS', //accessKeySecret of your own account
 bucket: 'a******io', //bucket name});

Placing the above information on the front end may cause security issues. If used in a project, it should be provided by the back-end interface as much as possible. Or use STS temporary authorization. Not in the demo, please explore it yourself.
https://www.alibabacloud.com/help/zh/doc-detail/100624.htm?spm=a2c63.p38356.879954.5.7a234d04IQpf5I#concept-xzh-nzk-2gb

You can ask the backend or operation and maintenance for the information in the configuration items. The bucket name must exist on your OSS and you have permission to access it. Otherwise, it will always report Pleasr create a busket first or "Cross-domain"

When encountering cross-domain or error messages with etag , please check the OSS configuration and find someone with OSS server permissions to configure it:

window.addEventListener('online', this.resumeUpload) is used to monitor the network status (disconnected and connected). To achieve automatic upload after resuming the network after disconnection, you must set the listener.

window.removeEventListener('online', this.resumeUpload) cancels the listener. If you do not set the cancel monitoring, the upload will continue when connected to the Internet, because the monitoring conditions are always met.

headers: {
   'Content-Disposition': 'inline',
   'Content-Type': this.file.type //Note: set according to the suffix of the image or file. I get the type of the file. The specific reason is explained below},

'Content-Type': this.file.type` function: After the file is uploaded, you can view it directly when accessing the file link, otherwise it will be downloaded directly.

After the file is uploaded, you can check it in resule.res.requestUrls, but be careful to click on the ?uploadId=****** after the address

The above code is just a demo. The code is mainly for implementing functions and is not rigorous. Please improve it by yourself.

This is the end of this article about vue+element+oss to implement front-end segmented upload and breakpoint resume. For more related vue segmented upload and breakpoint resume content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • 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)
  • Vue uses OSS to upload pictures or attachments

<<:  mysql 5.7.5 m15 winx64.zip installation tutorial

>>:  Detailed explanation of Nginx's control over access volume

Recommend

The basic principles and detailed usage of viewport

1. Overview of viewport Mobile browsers usually r...

How to use node scaffolding to build a server to implement token verification

content Use scaffolding to quickly build a node p...

mysql5.7.17.msi installation graphic tutorial

mysql-5.7.17.msi installation, follow the screens...

CentOS 8.0.1905 installs ZABBIX 4.4 version (verified)

Zabbix Server Environment Platform Version: ZABBI...

Introduction to basic concepts and technologies used in Web development

Today, this article introduces some basic concept...

A brief discussion on this.$store.state.xx.xx in Vue

Table of contents Vue this.$store.state.xx.xx Get...

How to open ports to the outside world in Alibaba Cloud Centos7.X

In a word: if you buy a cloud server from any maj...

Summary of Vue component basics

Component Basics 1 Component Reuse Components are...

How to deeply understand React's ref attribute

Table of contents Overview 1. Creation of Refs ob...

Detailed explanation of when javascript scripts will be executed

JavaScript scripts can be embedded anywhere in HT...

Native JS to implement hover drop-down menu

JS implements a hover drop-down menu. This is a s...

How to modify the location of data files in CentOS6.7 mysql5.6.33

Problem: The partition where MySQL stores data fi...