<!--
action是必要属性
http-request替代action自定义上传
on-preview是当文件上传时的狗子函数可接收两个参数file 和fileList,分别表示的是上传的那个文件和上传以后新的文件列表
on-remove是当移除文件时的狗子函数,可接受两个参数file 和fileList,分别表示的时移除的那个文件和移除后的文件列表
before-upload是在文件上传是的狗子函数,可接收参数file表示上传的当前文件
list-type是设置文件的的显示方式
-->
<div>
<h3>文件上传测试</h3>
<el-upload
action="#"
:http-request="uploadFn"
list-type="picture-card"
:class="{ showNone: 1 === 1 }"
:file-list="fileList"
:on-preview="onPreview"
:on-remove="onRemove"
:before-upload="beforeUpload"
>
<i class="el-icon-plus" />
</el-upload>
</div>
</template>
<script>
// 引入腾讯云上床插件
import COS from 'cos-js-sdk-v5'
// 拆建上传对象
const cos = new COS({
SecretId: 'AKIDDF1WkhNnwoQlpc8NL2ScV6QZPyGH2Wid',
SecretKey: 'h7G7i13qMchZ9SUFjvrWtzoMcbJkumNl'
})
export default {
props: {
// 定义一个用来控制接收文杰个数的变量,默认为一个
limit: {
type: Number,
default: 1
}
},
data() {
return {
fileList: []
}
},
methods: {
// 文件上传时更新文件列表
onPreview(file, newFileList) {
// 将新的文件列表覆盖旧的文件列表
this.fileList = newFileList
console.log('上传的的当前图片', file)
},
// 文件移除时更新文件列表
onRemove(file, newFileList) {
// 将新的文件列表覆盖旧的文件列表
this.fileList = newFileList
},
// 文件上传之前做些事情,可接收参数file指的是当前上传的文件
beforeUpload(file) {
// 这里限制上传的文件的大小,判断文件大于1MB时阻止上传
console.log('在上传之前做的事', file)
if (file.size > 1024 * 1024) {
// 弹框提示,图片文件大小不得大于1MB
this.$message.error('图片文件大小不得超过1MB')
return false
}
},
// data是上传文件对象
uploadFn(parmas) {
console.log(parmas)
// fileList是用图片上传的file-list绑定的值
cos.putObject(
{
Bucket: 'hr-79-1313468568' /* 必须 */,
Region: 'ap-guangzhou' /* 存储桶所在地域,必须字段 */,
Key: parmas.file.name /* 必须,key用图片的名字来设置 */,
StorageClass: 'STANDARD',
Body: parmas.file // 上传文件对象
},
// 使用箭头函数,使其this的指向是vue对象
(err, data) => {
// 判断上传是否出现错误
if (!err) {
// 如果没有错误就将对应的本地的图片路径改为线上的路径
this.fileList.forEach((image) => {
// 找到对应的图片
if (image.uid === parmas.file.uid) {
// 将网上的路径覆盖本地的路径
image.uid = 'http://' + data.location
}
})
} else {
this.$message.error('上传失败')
}
// this.fileList.push({
// url: 'http://' + data.Location
// })
}
)
}
}
}
</script>
<style>
</style>