前端vue+element ui文件上传操作。
1、vue项目安装依赖
npm install ali-oss
2、设置OSS支持PUT跨域请求
文件上传公共方法oss.js
let OSS = require('ali-oss');
let client = new OSS({
region: 'oss-cn-shanghai', //服务器的地区
accessKeyId: 'xxxxxxxx',
accessKeySecret: 'xxxxxxxxxxxx',
bucket: 'iweb-web' // OSS文件路径
});
let fileOperation = {
putFile (objectUrl, file) {
return new Promise((resolve, reject) => {
client.put(objectUrl, file).then(res => {
if(res.res.status === 200) {
resolve(res)
}
}).catch(err =>{
console.log('文件上传err---',err)
})
})
},
}
export default fileOperation;
使用公共方法
imgList.vue
<el-upload
class="upload-demo"
action="#"
:on-change="getFile"
:auto-upload="false"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
list-type="picture-card"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
imgList.js
import oss from '../../utils/oss.js'
export default {
data: function() {
return {
fileList: [{
name: 'food.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
}, {
name: 'food2.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
}]
};
},
mounted() {},
methods: { // 上传图片操作
getFile(file) {
console.log('file----', file) if (file) {
if (!/(\.png|\.gif|\.jpeg|\.jpg)/i.test(file.name)) {
this.$message.warning('请上传图片格式文件!');
return;
}
let date =
new Date();
// 保存的文件路径
let objectUrl = "/img/" + date.getFullYear() + "-" + (date.getMonth() + 1) + "/" + file.name;
file.raw.url = objectUrl;
oss.putFile(objectUrl, file.raw).then(res => {
if (res.res.status === 200) {
this.$message.success('上传成功');
file.url = res.url;
this.fileList.push(file)
} else {
this.$message.error('上传失败');
}
}).catch(err => {
this.$message.error('上传失败err---', err);
})
} else {
return;
}
},
// 删除文件
handleRemove(file, fileList) {
console.log('1---', file, fileList);
},
// 放大查看图片
handlePreview(file) {
console.log('2---', file);
},
}
};
注:上传成功可以继续调用nodejs接口将图片分组图片url添加到数据库中操作。