标签:callback ogr 回调 默认 rand 文件上传 splice for headers
<template>
<div>
<div id="container">
<button id="selectfiles" type="primary" class="btn">选择文件</button>
<template id="postfile" />
<button type="primary" class="btn" @click="postfiles">开始上传</button>
</div>
<div class="text">只能上传{{ acceptFiles }}格式文件,且不超过10M</div>
<!-- <pre id="console" /> -->
<!-- <h4>您所选择的文件列表:</h4> -->
<!-- <div id="ossfile">你的浏览器不支持flash,Silverlight或者HTML5!</div> -->
<div v-if="fileRawList.length>0" :class="fileRawList.length>1?‘fileList‘:‘‘">
<div v-for="(item,index) in fileRawList" :key="index" class="plupload_list">
<div style="width:75vw;">{{ item.name }}</div>
<div @click="deleteFile(item)">X</div>
</div>
</div>
</div>
</template>
<script>
import plupload from ‘plupload‘
import { getSignature, uploadFileName } from ‘@/api/test‘
export default {
name: ‘ImgUpload‘,
props: {
// 文件上传类型限制
acceptFiles: {
type: String,
default: ‘.jpg,.png,.jpeg,.gif,.bmp,.ppt,.pptx,.doc,.docx,.xls,.xlsx,.txt‘
},
fileList: {
type: Array,
default: () => []
},
limit: {
type: Number,
default: 1
}
},
data() {
return {
accessid: ‘‘,
accesskey: ‘‘,
host: ‘‘,
policyBase64: ‘‘,
signature: ‘‘,
callbackbody: ‘‘,
fileName: ‘‘,
key: ‘‘,
expire: 0,
g_object_name: ‘‘,
g_object_name_type: ‘random_name‘,
now: Date.parse(new Date()) / 1000,
timestamp: Date.parse(new Date()) / 1000,
uploaders: {},
fileRawList: [],
loading: false,
percent: ‘‘,
dir: ‘‘
}
},
watch: {
uploaders(val) {
console.log(‘up‘, val)
this.fileRawList = this.fileList.concat(val.files)
},
acceptFiles(val) {
this.uploaders.refresh()
}
},
mounted() {
this.uploadInit()
},
methods: {
uploadInit() {
var that = this
var uploader = new plupload.Uploader({
runtimes: ‘html5,flash,silverlight,html4‘,
browse_button: ‘selectfiles‘,
// multi_selection: false,
container: document.getElementById(‘container‘),
/* flash_swf_url: ‘../../../assets/plupload-2.1.2/js/Moxie.swf‘,
silverlight_xap_url: ‘../../../assets/plupload-2.1.2/js/Moxie.xap‘, */
url: ‘http://oss-cn-gz-csa-d01-a.inner.y.csair.com‘,
filters: {
mime_types: [
// 只允许上传图片和zip文件
{ extensions: that.acceptFiles.replace(/\./g, ‘‘) }
],
max_file_size: ‘10mb‘, // 最大只能上传10mb的文件
prevent_duplicates: true // 不允许选取重复文件
},
headers: {
‘x-oss-forbid-overwrite‘: true
},
init: {
PostInit: function() {
/* document.getElementById(‘ossfile‘).innerHTML = ‘‘
document.getElementById(‘postfiles‘).onclick = function() {
that.set_upload_param(uploader, ‘‘, true)
return false
} */
that.postfiles()
},
FilesAdded: function(up, files) {
// console.log(‘FilesAdded‘, files)
that.fileRawList = files
if (that.fileRawList.length > that.limit) {
that.deleteFile(that.fileRawList[0])
that.$message({
message: ‘上传的最大文件数为:‘ +
that.limit + ‘个‘,
type: ‘warning‘
})
}
/* plupload.each(files, function(file) {
document.getElementById(‘ossfile‘).innerHTML +=
‘<div class="plupload_list"><div id="‘ +
file.id +
‘" style="width:80vw">‘ +
file.name +
‘ (‘ +
plupload.formatSize(file.size) +
‘)<b></b>‘ +
‘<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>‘ +
‘</div>‘ + ‘<div>X</div>‘ + ‘</div>‘
}) */
},
BeforeUpload: function(up, file) {
// that.check_object_radio()
that.set_upload_param(file.name, true)
},
/* UploadProgress: function(up, file) {
that.percent = parseInt(file.percent) + ‘%‘
console.log(up, file, ‘UploadProgress‘)
var d = document.getElementById(file.id)
d.getElementsByTagName(‘b‘)[0].innerHTML =
‘<span>‘ + file.percent + ‘%</span>‘
var prog = d.getElementsByTagName(‘div‘)[0]
var progBar = prog.getElementsByTagName(‘div‘)[0]
progBar.style.width = 2 * file.percent + ‘px‘
progBar.setAttribute(‘aria-valuenow‘, file.percent)
}, */
FileUploaded: function(up, file, info) {
// console.log(up, file, info, ‘info‘)
if (info.status == 200) {
that.$message({
message: ‘上传成功‘,
type: ‘success‘
})
that.fileRawList = []
that.uploadFileInfo()
that.$emit(‘uploadSuccess‘)
} else if (info.status == 203) {
that.$message(
‘上传成功,但是上传回调服务器失败,失败原因是:‘ +
info.response
)
} else {
that.$message(info.response)
}
},
Error: function(up, err) {
that.uploading = false
if (err.code == -600) {
that.$message.error(
‘选择的文件太大了‘
)
} else if (err.code == -601) {
that.$message.error(
‘选择的文件后缀不对‘
)
} else if (err.code == -602) {
that.$message.error(‘这个文件已经在文件列表中‘)
} else {
that.$message.error(‘上传失败请,请稍候重试‘)
}
},
FilesRemoved(upp, files) {
that.uploading = false
},
UploadComplete(up, files) {
up.splice()
up.refresh()
that.uploading = false
}
}
})
uploader.init()
this.uploaders = uploader
},
uploadFileInfo() {
// const bool = this.get_signature()
// if (bool) {
const obj = {
newObjectName: this.key,
oldObjectName: this.fileName,
folderName: this.dir,
bucketName: ‘‘,
fileUrl: ‘‘
}
uploadFileName(obj).then(res => {
console.log(res)
if (res.success == true) {
// 存入数据库成功
} else {
// 存入数据库失败
// this.uploadFileInfo()
}
})
// }
},
deleteFile(row) {
this.fileRawList.splice(this.fileRawList.indexOf(row), 1)
var file = this.uploaders.getFile(row.id)
file && this.uploaders.removeFile(file)
this.$emit(‘onChange‘, this.fileRawList.filter(item => {
return item.url
}))
/* if (res.success) {
return
} */
},
postfiles() {
this.uploading = true
if (this.fileRawList.length > 0) {
this.fileName = this.fileRawList[0].name
this.get_signature()
}
return false
},
/* send_request() {
return getSignature()
}, */
/* check_object_radio() {
this.g_object_name_type = ‘random_name‘
var tt = document.getElementsByName("myradio");
for (var i = 0; i < tt.length; i++) {
if (tt[i].checked) {
this.g_object_name_type = tt[i].value;
break;
}
}
}, */
get_signature() {
// 可以判断当前expire是否超过了当前时间, 如果超过了当前时间, 就重新取一下,3s 作为缓冲。
// this.now = this.timestamp = Date.parse(new Date()) / 1000
// if (this.expire < this.now + 1) {
var formData = new FormData()
formData.append(‘orgFileName‘, this.fileName)
getSignature(formData).then(res => {
this.host = res.host
this.policyBase64 = res.policy
this.accessid = res.accessKeyId
this.signature = res.signature
this.expire = res.expire
this.callbackbody = res.callback
this.key = res.dir
this.dir = res.data
this.set_upload_param(‘‘, true)
})
/* console.log(body, ‘body‘)
this.newFileName = body.data */
return true
// }
// return false
},
/* random_string(len) {
len = len || 32
var chars = ‘ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz23456789‘
var maxPos = chars.length
var pwd = ‘‘
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos))
}
return pwd
}, */
get_suffix(filename) {
const pos = filename.lastIndexOf(‘.‘)
let suffix = ‘‘
if (pos != -1) {
suffix = filename.substring(pos)
}
return suffix
},
/* calculate_object_name(filename) {
if (this.g_object_name_type == ‘local_name‘) {
this.g_object_name += ‘${filename}‘
} else if (this.g_object_name_type == ‘random_name‘) {
const suffix = this.get_suffix(filename)
this.g_object_name = this.key + this.random_string(32) + suffix
}
return ‘‘
}, */
/* get_uploaded_object_name(filename) {
if (this.g_object_name_type == ‘local_name‘) {
let tmp_name = this.g_object_name
tmp_name = tmp_name.replace(‘${filename}‘, filename)
return tmp_name
} else if (this.g_object_name_type == ‘random_name‘) {
return this.g_object_name
}
}, */
set_upload_param(filename, ret) {
if (ret == false) {
ret = this.get_signature()
}
/* this.g_object_name = this.key
if (filename != ‘‘) {
// const suffix = this.get_suffix(filename)
this.calculate_object_name(filename)
} */
// eslint-disable-next-line no-unused-vars
const name = this.key + this.newFileName + this.get_suffix(filename)
// if (ret) {
const new_multipart_params = {
key: this.key,
policy: this.policyBase64,
OSSAccessKeyId: this.accessid,
success_action_status: ‘200‘, // 让服务端返回200,不然,默认会返回204
callback: this.callbackbody,
signature: this.signature
}
this.uploaders.setOption({
url: this.host,
multipart_params: new_multipart_params
})
this.uploaders.start()
// }
}
}
}
</script>
<style lang="scss" scoped>
.btn {
background-color: #409eff;
height: 30px;
font-size: 12px;
color: #fff;
border-radius: 4px;
overflow: hidden;
border: none;
padding: 0 15px;
margin: 0px 5px;
}
.text{
font-size: 12px;
color: #666;
line-height: 15px;
padding: 5px 0px;
}
.plupload_list{
width: 95%;
padding: 10px 10px;
border: 1px solid #999;
border-radius: 4px;
margin: 5px 0;display:flex;
display: flex;
align-items: center;
}
.fileList{
max-height: 200px;
overflow-x: hidden;
border: 1px solid #999;
border-radius: 4px;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}
</style>
Vue中使用七牛云上传报错o.upload.addEventListener is not a function以及其他报错问题
主要的原因是mock.js重写了http请求
解决方案1
标签:callback ogr 回调 默认 rand 文件上传 splice for headers
原文地址:https://www.cnblogs.com/taoyuanju/p/13126410.html