上传到OSS服务器
先安装依赖
npm install ali-oss --save
写oss.js
let OSS = require('ali-oss')
export let client = new OSS({
region:'oss-cn-hangzhou', //一般都是这个不需要改
accessKeyId:'*******',
accessKeySecret:'*******',
bucket:'weishenme' //存储空间的名字
})
在你的页面中写上组件与方法
<el-upload
class="upload-demo"
action="https://xxx.oss-cn-hangzhou.aliyuncs.com/" //改成你的,也可以补写,但是action也留着
:file-list="filesList"
list-type="picture"
:http-request="httpRequest"
:limit=1
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
import {client} from '../../../../api/oss.js'
export default {
data() {
return {
filesList: [],
}
},
methods:{
httpRequest (e) {
let file = e.file // 文件信息
if (!file) {
return false
} else if (!/\.(png|jpg)$/.test(file.name.toLowerCase())) {
// 格式根据自己需求定义
this.$message.error('上传格式不正确,请上传png或者jpg格式')
return false
}
this.getCurrentTime()
//给上传的文件起名字 现在的时间戳+本来的名字
let filename = new Date().getTime()+file.name
client.put(filename, file).then(res =>{
idenApi.upload(this.record.id,filename).then(ress =>{
this.$message({
showClose: true,
message: '上传成功',
type: 'success'
});
})
console.log(res.url)
})
},
}
}
指定目录上传
//指定目录 路径+文件名
client.put('/fjzy/'+filename, file)
完成!
后端代码就储存了文件名称!
@PostMapping("/upload/{id}/{fileName}")
public Result upload(
@PathVariable("id") String id,
@PathVariable("fileName") String fileName) {
AppraisalSmokeFeedbackRecord af = appraisalSmokeFeedbackRecordService.getById(id);
af.setReportOss(fileName);
appraisalSmokeFeedbackRecordService.updateById(af);
return ResultFactory.buildSuccessResult("上传成功");
}