Vue Element UI + OSS实现上传文件功能

时间:2021-05-26

Element提供了upload上传组件,可以查看官网upload组件的详细介绍;查看upload组件的上传源码upload/ajax,使用的是XHR对象上传文件。在项目实践中,发现该上传方法上传大文件时会出现问题,所以决定使用阿里云对象存储服务(Object Storage Service,简称OSS),OSS详细介绍可以查看官网,本文主要讲解的是OSS上传文件的前端,后台开发请查看官网介绍,SDK Browser.js讲解了前端如何进行上传。

1、使用npm安装SDK的开发包:

npm install ali-oss

2、OSS配置

let OSS = require('ali-oss');let client= new OSS.Wrapper({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou'});

最新版的没有了Wrapper构造函数,直接配置

let oss = require('ali-oss');var client = oss({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou'});

3、上传文件

OSS上传文件分为上传Buffer内容、上传blob数据、分片上传,此处展示分片上传

let result = await client.multipartUpload('object-key', 'local-file', { progress: async function (p) { console.log('Progress: ' + p); } });

js调用OSS上传文件已经没有问题,但是我们需要实现公用上传组件,Element UI已经实现了Upload上传组件,包括上传进度、异常处理、拖拽等;那我们还有必要重新开发一个像Upload一样的组件吗?通过查看Upload组件的API发现有一个http-request属性,http-request覆盖默认的上传行为,可以自定义上传的实现;看到这个我就省了很多事,直接用OSS上传覆盖XHR上传。代码如下:

<template> <div> <el-upload :auto-upload="false" :action="uploadUrl" ref="upload" :before-upload="fnBeforeUpload" :on-success="fnUploadSuccess" :on-exceed="fnUploadExceed" :data="data_extra" :headers="uploadHeaders" :http-request="fnUploadRequest" drag :limit="files" :disabled="disabled" multiple> <i class="el-icon-upload"></i> <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div> <div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div> </el-upload> </div></template><script>import UploadFileApi from '@/api/system/UploadFileApi'import * as util from 'utils/common'import OSS from 'ali-oss'export default { name: 'fileUpload', props: { data_extra: { type: Object, required: true }, accept: { type: Array, required: true } }, data () { return { uploadUrl: '', uploadFileLength: 0, uploadFileSuccess: 0, uploadFileNames: [], uploadFileName: [], fileList: [], files: 10, uploadHeaders: { authorization: '' }, disabled: false } }, methods: { /** * @description [fnUploadRequest 覆盖默认的上传行为,实现自定义上传] * @author shanshuizinong * @param {object} option [上传选项] * @return {null} [没有返回] */ async fnUploadRequest (option) { try { let vm = this vm.disabled = true // 获取OSS配置信息 let uploadFileApi = new UploadFileApi() let ret = await uploadFileApi.fileOssParams() if (!(ret.data && ret.data.code === '0' && ret.data.data)) { throw new Error('获取OSS参数失败') } let ossData = JSON.parse(ret.data.data) let relativePath = ossData.relativePath let client = new OSS.Wrapper({ policy: ossData.policy, accessKeyId: ossData.accessid, accessKeySecret: ossData.accesssecret, bucket: ossData.bucket, signature: ossData.signature }) let file = option.file const point = file.name.lastIndexOf('.') let suffix = file.name.substr(point) let fileName = file.name.substr(0, point) let date = vm.$moment().format('YYYYMMDDHHmm') let fileNames = `${fileName}_${date}${suffix}` // 分片上传文件 ret = await client.multipartUpload(relativePath + fileNames, file, { progress: async function (p) { let e = {} e.percent = p * 100 option.onProgress(e) } }) console.log(ret) if (ret.res.statusCode === 200) { // option.onSuccess(ret) return ret } else { vm.disabled = false option.onError('上传失败') } } catch (error) { console.error(error) this.disabled = false option.onError('上传失败') this.$error(error.message) } }, /** * @description [fnUploadSuccess 文件上传成功的函数] * @author shanshuizinong * @return {null} [没有返回] */ async fnUploadSuccess () { // TODO } }}</script>

查看upload源码upload.vue知道httpRequest会有一个文件上传的option选项作为参数,upload/ajax源码中上传进度、上传成功、上传失败都是通过option调用其方法进行触发。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章