下面是“Vue Element UI + OSS实现上传文件功能”的完整攻略。
准备工作
1.安装Vue CLI并创建Vue项目。
2.引入Element UI和Aliyun OSS SDK。
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue Element UI + OSS实现上传文件功能</title>
</head>
<body>
<div id="app"></div>
<!-- 引入Element UI -->
<link rel="stylesheet" href="//unpkg.com/element-ui/lib/theme-chalk/index.css">
</body>
<script src="/static/js/oss-sdk.js"></script>
<script src="//cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="//unpkg.com/element-ui/lib/index.js"></script>
<script src="./app.js"></script>
</html>
3.编写初始化OSS控制台信息的方法。
// app.js
const OSS = require('ali-oss').Wrapper;
Vue.prototype.$osssts = {
region: '',
accessKeyId: '',
accessKeySecret: '',
bucket: '',
stsToken: '',
expiration: '',
};
Vue.prototype.$ossClient = {};
Vue.prototype.$initOss = function () {
let self = this;
this.$http.get('/api/sts').then(response => {
if (response.status === 200 && response.data.Code === 'Success') {
let data = response.data;
self.$osssts.accessKeyId = data.AccessKeyId;
self.$osssts.accessKeySecret = data.AccessKeySecret;
self.$osssts.securityToken = data.SecurityToken;
self.$osssts.expiration = data.Expiration;
self.$osssts.region = self.$configStore.get('oss.region');
self.$osssts.bucket = self.$configStore.get('oss.bucket');
self.$ossClient = new OSS({
region: self.$osssts.region,
accessKeyId: self.$osssts.accessKeyId,
accessKeySecret: self.$osssts.accessKeySecret,
stsToken: self.$osssts.securityToken,
bucket: self.$osssts.bucket
});
}
})
}
Element-Ui Upload 组件的使用
Element-Ui提供了Upload组件,可以非常方便地实现文件上传功能。
使用vue-cli安装 Element UI
npm install element-ui --save
引入Upload组件
<!--index.html-->
<div id="app">
<el-upload
class="upload-demo"
action="//jsonplaceholder.typicode.com/posts/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:on-error="handleError"
:before-upload="beforeUpload">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
配置actions
action属性是上传的接收地址,这里我们需要将其配置到OSS上。
<!--index.html-->
<template>
<div id="app">
<el-upload
class="upload-demo"
:action="$ossClient.signatureUrl('test/image')"
:on-success="handleSuccess"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件...</div>
</el-upload>
</div>
</template>
调用OSS相关API实现上传功能
上传文件
// app.js
Vue.prototype.$uploadOss = function (file, options = {}) {
let ext = file.name.substr(file.name.lastIndexOf('.'));
let storeName = options.storeName || Date.now().toString() + ext;
return Promise.all([
this.$ossClient.put(storeName, file),
Promise.resolve(storeName),
this.$configStore.get('oss.url') + '/' + storeName,
]);
};
删除文件
// app.js
Vue.prototype.$removeOss = function (key) {
return this.$ossClient.delete(key);
};
完整示例
<!--index.html-->
<template>
<div id="app">
<el-upload
class="upload-demo"
:action="$ossClient.signatureUrl('test/image')"
:on-success="handleSuccess"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件...</div>
</el-upload>
<el-table
style="width: 100%;"
:data="fileList"
border
v-loading="loading"
:default-sort="sortObj"
height="500"
@sort-change="handleSortChange">
<el-table-column fixed="left" label="文件名" width="200">
<template slot-scope="{ row }">
<a :href="$configStore.get('oss.url')+'/'+row.storeName">{{row.storeName}}</a>
</template>
</el-table-column>
<el-table-column fixed="left" prop="fileSize" label="文件大小" width="100">
<template slot-scope="{ row }">
{{(row.fileSize/1024).toFixed(2)}} K
</template>
</el-table-column>
<el-table-column prop="lastModified" label="上传时间" width="150" sortable>
<template slot-scope="{ row }">
{{ dateFormat(row.lastModified) }}
</template>
</el-table-column>
<el-table-column label="操作" width="150" fixed="right">
<template scope="scope">
<el-button type="danger" size="mini" :loading="scope.row.loading" @click="removeFile(scope.row, scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
loading: false,
fileList: [],
sortObj: {
prop: 'lastModified',
order: 'descending'
}
}
},
created () {
this.$initOss();
this.getFileList();
},
computed: {
$fileStore () {
return this.$store.state.files;
}
},
methods: {
handleSuccess (response, file, fileList) {
if (response.res.status === 200) {
let file = {
storeName: response.name,
fileSize: file.size,
fileExtension: file.name.replace(/.*\./, ''),
lastModified: Date.now()
};
this.addFile(file);
} else {
this.$message.error('上传失败!');
}
},
addFile (file) {
this.$fileStore.addFile(file).then(data => {
this.getFileList();
});
},
getFileList () {
this.loading = true;
let self = this;
this.$fileStore.getFileList().then(data => {
self.fileList = data;
self.loading = false;
});
},
removeFile (file, index) {
this.$fileStore.removeFile(file).then(() => {
this.fileList.splice(index, 1);
});
},
dateFormat (timestamp) {
let date = new Date(timestamp);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hours = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
return `${year}-${month}-${day} ${hours}:${minute}:${second}`;
},
handleSortChange ({ prop, order }) {
this.fileList.sort((a, b) => {
let valueA = a[prop];
let valueB = b[prop];
if (order === 'descending') {
return valueB - valueA;
} else {
return valueA - valueB;
}
})
}
}
}
</script>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Vue Element UI + OSS实现上传文件功能 - Python技术站