我是靠谱客的博主 友好钢笔,最近开发中收集的这篇文章主要介绍vue断点续传上传文件到oss,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

首先了解断点续传原理,其次对vue-simple-upload插件进行再度封装使用。这是一个待优化案例,不过是可以实现功能的。附上源码,仅供参考:

<template>
<div class="uploader-demo">
<!--文件回显-->
<div class="show-file">
<img v-if="pdfId"
@click="showPDF" src="../../../assets/images/pdf.png" alt="">
</div>
<uploader
ref="uploader"
:file-status-text="statusText"
class="uploader-example"
enctype="multipart/form-data"
@upload-start="myOss"
@file-removed="removeFile"
@file-complete="fileComplete"
@complete="complete"
@file-success="fileSuccess">
<uploader-drop>
<uploader-btn :single="singleFile">上传</uploader-btn>
</uploader-drop>
<!--<span @click="downLoadFile">下载</span>-->
<!--<span @click="delFile">删除</span>-->
</uploader>
<!--查看pdf-->
<div
v-if="isshowpdf"
class="check-pdf-wrap"
@click="hiddenPdf">
<iframe
:src="myPdfUrl"
class="check-pdf"
width="100%"
scrolling="no">
您的浏览器不支持框架
</iframe>
</div>
</div>
</template>
<script>
import {$get, $post, $put} from '../../../javascript/utils/http';
export default {
props:{
index:Number,
pdfId:String,
dir:String,
format:String
},
data() {
return {
fileFormat:this.format,
ossDir:this.dir,
mypdfId:this.pdfId,
myPdfUrl:'',
isshowpdf:'',
myFileName: '',
fileId: '',
myFile: '',
oss:{
region: '',
endpoint: '',
accessKeyId: '',
accessKeySecret: '',
bucket: '',
dir:''
},
fileText: '文件回显',
statusText: {
success: '成功',
error: '失败',
uploading: '上传中',
paused: '暂停',
waiting: '等待'
},
attrs: {
accept: 'pdf/*'
},
singleFile:true,
percentage: 0,
url: '',
uploadFilesName: '',
uploadfile: [],
maxLength: 1,
needDisabled: true
}
},
mounted() {
this.$nextTick(() => {
window.uploader = this.$refs.uploader.uploader
})
},
methods: {
myOss(){
$get(`/common/file/get-oss-param?dir=${this.ossDir}`).then((res)=>{
this.oss.region = res.data.region
this.oss.endpoint = res.data.endpoint
this.oss.accessKeyId = res.data.accessKeyId
this.oss.accessKeySecret = res.data.accessKeySecret
this.oss.bucket = res.data.bucket
this.oss.dir = res.data.dir
}).then(()=>{
this.toUpload()
}).catch(() => {})
},
downLoadFile(){
$get(`/common/get-oss-url/${this.fileId}`).then((res) => {
// client.get('').then(() => {
//
alert(1)
// })
}).catch()
},
toBlob(urlData, fileType) {
const bytes = window.atob(urlData)
let n = bytes.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bytes.charCodeAt(n)
}
return new Blob([u8arr], { type: fileType })
},
toUpload() {
console.log('===================开始上传========================')
const vthis = this
// 进度
this.percentage = 0;
// 获取文件信息
const files = this.$refs.uploader
if (files.files) {
const fileLen = this.$refs.uploader.files
const file = this.$refs.uploader.files[0]
let consat = file.name;
// 限制上传的文件格式
if (consat.indexOf(this.fileFormat) > -1) {
} else {
vthis.$message.error('格式不正确,请上传对应的格式。');
fileLen.length = 0;
return false;
}
//限制上传文件的个数
const check = fileLen.length <= vthis.maxLength;
if (!check) {
fileLen.length = 0;
}
// 配置oss
const OSS = require('ali-oss')
const client = new OSS({
region: this.oss.region,
endpoint: this.oss.endpoint,
accessKeyId: this.oss.accessKeyId,
accessKeySecret: this.oss.accessKeySecret,
bucket: this.oss.bucket
})
// 图像数据 (e.g. data:image/png;base64,iVBOR...yssDuN70DiAAAAABJRU5ErkJggg==)
const myfile = fileLen[0].file
const name = fileLen[0].name
let reader = new FileReader();
reader.readAsDataURL(myfile)
setTimeout(() => {
// 需要注意:必须等转换成功后才可以取出来result
const dataUrl = reader.result
console.log(dataUrl)
const base64 = dataUrl.split(',')[1]
const fileType = dataUrl.split(';')[0].split(':')[1]
// base64转blob
const blob = this.toBlob(base64, fileType)
// blob转arrayBuffer
// let reader = new FileReader();
reader.readAsArrayBuffer(blob)
reader.onload = function (e) {
// arrayBuffer转Buffer e.target.result是文件的完整Base64 Data-URI
const buffer = new OSS.Buffer(e.target.result);
const myUuid = vthis.uuid()
const fileName = vthis.oss.dir+ myUuid +name
// 上传 https://help.aliyun.com/document_detail/32070.html?spm=a2c4g.11186623.2.10.2fcd59d4meCSTS
client.put(fileName, buffer).then(function (res) {
res.pdfName = name;
res.index = vthis.index
console.log(res)
// 上传成功后,发送给后台文件信息:文件名/文件大小/格式/路径
vthis.$emit('savefileId', res)
fileLen.length = 0;
}).catch(function (err) {
vthis.$message.error('上传失败')
console.log(err);
});
}
}, 500)
}
},
uuid(){
let s = [];
let hexDigits = "0123456789abcdef";
for (let i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
// bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
// bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "";
let uuid = s.join("");
return uuid;
},
delFile(){
// 配置oss
const OSS = require('ali-oss')
const client = new OSS({
region: this.oss.region,
endpoint: this.oss.endpoint,
accessKeyId: this.oss.accessKeyId,
accessKeySecret: this.oss.accessKeySecret,
bucket: this.oss.bucket
})
client.delete(this.myFileName).then((res) => {
this.$message.success(`已成功删除${this.myFileName}`)
}).catch((err) => {
this.$message.success(`删除${this.myFileName}失败`)
})
},
removeFile(file) {
// console.log('======================删除文件============================', file)
},
complete() {
// console.log('=====================加载完成============================', arguments)
},
fileComplete() {
// console.log('====================文件加载完成=========================', arguments)
},
// 上传成功的事件
fileSuccess(rootFile, file, message, chunk) {
// console.log('=====================文件上传成功=======================', rootFile, file, message, chunk)
},
// 点击图标,查看pdf
showPDF(){
$get(`/common/get-oss-url/${this.mypdfId}`).then((res) => {
this.myPdfUrl = res.data.fileUrl
this.isshowpdf = !this.isshowpdf;
}).catch((err) => {})
},
hiddenPdf(){
this.isshowpdf = !this.isshowpdf;
}
}
}
</script>
<style scoped lang="less">
.uploader-demo{
position: relative;
.show-file{
position: absolute;
width: 44px;
height: 32px;
border: 1px dashed #ccc;
margin-right: 10px;
border-radius: 4px;
img{
height: 100%;
}
}
.uploader{
position: absolute;
bottom: -56px;
left: 60px;
}
.uploader-drop{
border: none;
padding: 0;
display: inline-block;
}
.uploader-btn{
padding: 0;
line-height: 38px;
text-align: center;
color: #64a7fb;
border: none;
background: #fff;
text-decoration: underline;
font-size: 12px;
}
.uploader-file{
/*display: none;*/
height: 44px;
line-height: 44px;
}
.uploader-list{
font-size: 12px;
}
.uploader-file-icon:before{
font-size: 18px;
}
.uploader-file-progress{
background-color: #fff;
}
}
</style>

使用:

// 1 html
<uploader @savefileId="savefileId" :pdfId="uploadForm.contractFile" :dir="ossDirContracts" :format="uploadFormat"/>
<el-input v-model="uploadForm.contractFile"
type="hidden"
placeholder="合同附件"></el-input>
// 2 html
<uploader @savefileId="savefilesId" :index=index :pdfId="uploadData[index].invoiceFile" :dir="ossDirInvoices" :format="uploadFormat"/>
<el-input v-model="uploadData[index].invoiceFile"
type="hidden"
placeholder="发票附件"></el-input>
//data
uploadFormat:'.pdf',
ossDirContracts:"contracts",
ossDirInvoices:"invoices",
// methods
savefileId(file){
$post('/common/file/save-upload-oss',{
fileName: file.pdfName,
fileSize: 0,
fileType: 'pdf',
fileUri: file.name
}).then((res) => {
this.uploadForm.contractFile = res.data.fileId;
this.$message.success('上传成功')
}).catch(() => {})
},
savefilesId(file){
$post('/common/file/save-upload-oss',{
fileName: file.pdfName,
fileSize: 0,
fileType: 'pdf',
fileUri: file.name,
index: file.index
}).then((res) => {
// 获取fileId并赋值给相对应的input框
let index = res.data.index;
this.uploadData[index].invoiceFile = res.data.fileId;
this.$message.success('上传成功')
}).catch(() => {})
},

最后

以上就是友好钢笔为你收集整理的vue断点续传上传文件到oss的全部内容,希望文章能够帮你解决vue断点续传上传文件到oss所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部