element ui +spring boot + 阿里云oss对象存储 实现文件用户头像上传与在线修改
数据库里面存放的是头像的网络地址
阿里云购买oss对象存储、配置bucket、以及跨域问题
1、安装阿里云oss
npm install ali-oss
2、使用element-ui 默认的 upload组件,但是要重写http-request 方法
templeate部分:
<el-upload
:show-file-list="false"
:http-request="fnUploadRequest"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
3、script 使用oss、配置oss的连接
const OSS = require('ali-oss');
const client= new OSS({
accessKeyId: '', // 查看你自己的阿里云KEY
accessKeySecret: '', // 查看自己的阿里云KEYSECRET
bucket: '', // 你的 OSS bucket 名称
region: '', // bucket 所在地址,我的是 华东2 杭州
cname:true, // 开启自定义域名上传
endpoint:"" // 自己的域名
});
4、核心技术
//图片上传成功回调
handleAvatarSuccess(res) {
if (res) this.imageUrl = res.url
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
async fnUploadRequest(options) {
try {
let file = options.file; // 拿到 file
let fileName = file.name.substr(0,file.name.lastIndexOf('.'))
let date = new Date().getTime()
let fileNames = `${date}_${fileName}` // 拼接文件名,保证唯一,这里使用时间戳+原文件名
// 上传文件,这里是上传到OSS的 uploads文件夹下
client.put("headerimages/"+fileNames, file).then(res=>{
if (res.res.statusCode === 200) {
options.onSuccess(res)
}else {
options.onError("上传失败")
}
})
}catch (e) {
options.onError("上传失败")
}
},
init (id) {
this.dataForm.id = id || 0
this.visible = true
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
if (this.dataForm.id) {
this.$http({
url: this.$http.adornUrl(`/study/student/info/${this.dataForm.id}`),
method: 'get',
params: this.$http.adornParams()
}).then(({data}) => {
if (data && data.code === 200) {
this.dataForm.upwd = data.student.upwd
this.dataForm.uname = data.student.uname
this.dataForm.classid = data.student.classid
this.dataForm.header = data.student.header
}
})
}
})
},
// 表单提交
dataFormSubmit () {
this.$refs['dataForm'].validate((valid) => {
if (valid) {
this.$http({
url: this.$http.adornUrl(`/study/student/${!this.dataForm.id ? 'save' : 'update'}`),
method: 'post',
data: this.$http.adornData({
'id': this.dataForm.id || undefined,
'upwd': this.dataForm.upwd,
'uname': this.dataForm.uname,
'classid': this.dataForm.classid,
'header': this.imageUrl
})
}).then(({data}) => {
if (data && data.code === 200) {
this.$message({
message: '操作成功',
type: 'success',
duration: 1500,
onClose: () => {
this.visible = false
this.$emit('refreshDataList')
}
})
} else {
this.$message.error(data.msg)
}
})
}
})
}
完整代码
student.vue
<template>
<div class="mod-config">
<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
<el-form-item>
<el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
</el-form-item>
<el-form-item>
<el-button @click="getDataList()">查询</el-button>
<el-button v-if="isAuth('study:student:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
<el-button v-if="isAuth('study:student:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
</el-form-item>
</el-form>
<el-table
:data="dataList"
border
v-loading="dataListLoading"
@selection-change="selectionChangeHandle"
style="width: 100%;">
<el-table-column
type="selection"
header-align="center"
align="center"
width="50">
</el-table-column>
<el-table-column
prop="id"
header-align="center"
align="center"
label="学号(自增)">
</el-table-column>
<el-table-column
prop="upwd"
header-align="center"
align="center"
label="密码">
</el-table-column>
<el-table-column
prop="uname"
header-align="center"
align="center"
label="姓名">
</el-table-column>
<el-table-column
prop="classid"
header-align="center"
align="center"
label="班级">
</el-table-column>
<el-table-column prop="header" header-align="center" align="center" label="头像">
<template slot-scope="scope">
<!-- 自定义表格+自定义图片 -->
<img :src="scope.row.header" style="width: 100px; height: 80px" />
</template>
</el-table-column>
<el-table-column
fixed="right"
header-align="center"
align="center"
width="150"
label="操作">
<template slot-scope="scope">
<el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
<el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
@size-change="sizeChangeHandle"
@current-change="currentChangeHandle"
:current-page="pageIndex"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
:total="totalPage"
layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
<!-- 弹窗, 新增 / 修改 -->
<add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
</div>
</template>
<script>
import AddOrUpdate from './student-add-or-update'
export default {
data () {
return {
dataForm: {
key: ''
},
dataList: [],
pageIndex: 1,
pageSize: 10,
totalPage: 0,
dataListLoading: false,
dataListSelections: [],
addOrUpdateVisible: false
}
},
components: {
AddOrUpdate
},
activated () {
this.getDataList()
},
methods: {
// 获取数据列表
getDataList () {
this.dataListLoading = true
this.$http({
url: this.$http.adornUrl('/study/student/list'),
method: 'get',
params: this.$http.adornParams({
'page': this.pageIndex,
'limit': this.pageSize,
'key': this.dataForm.key
})
}).then(({data}) => {
if (data && data.code === 200) {
this.dataList = data.page.list
this.totalPage = data.page.totalCount
} else {
this.dataList = []
this.totalPage = 0
}
this.dataListLoading = false
})
},
// 每页数
sizeChangeHandle (val) {
this.pageSize = val
this.pageIndex = 1
this.getDataList()
},
// 当前页
currentChangeHandle (val) {
this.pageIndex = val
this.getDataList()
},
// 多选
selectionChangeHandle (val) {
this.dataListSelections = val
},
// 新增 / 修改
addOrUpdateHandle (id) {
this.addOrUpdateVisible = true
this.$nextTick(() => {
this.$refs.addOrUpdate.init(id)
})
},
// 删除
deleteHandle (id) {
var ids = id ? [id] : this.dataListSelections.map(item => {
return item.id
})
this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http({
url: this.$http.adornUrl('/study/student/delete'),
method: 'post',
data: this.$http.adornData(ids, false)
}).then(({data}) => {
if (data && data.code === 200) {
this.$message({
message: '操作成功',
type: 'success',
duration: 1500,
onClose: () => {
this.getDataList()
}
})
} else {
this.$message.error(data.msg)
}
})
})
}
}
}
</script>
student-add-or-update.vue
<template>
<el-dialog
:title="!dataForm.id ? '新增' : '修改'"
:close-on-click-modal="false"
:visible.sync="visible">
<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
<el-form-item label="密码" prop="upwd">
<el-input v-model="dataForm.upwd" placeholder=""></el-input>
</el-form-item>
<el-form-item label="姓名" prop="uname">
<el-input v-model="dataForm.uname" placeholder=""></el-input>
</el-form-item>
<el-form-item label="班级" prop="classid">
<el-input v-model="dataForm.classid" placeholder=""></el-input>
</el-form-item>
<el-upload
:show-file-list="false"
:http-request="fnUploadRequest"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
</span>
</el-dialog>
</template>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<script>
const OSS = require('ali-oss');
const client= new OSS({
accessKeyId: 'LTAI5t8BAFugx5Rhju18xVTT', // 查看你自己的阿里云KEY
accessKeySecret: 'FojJdHYFOmXbgAWKla0l91uckTS2z9', // 查看自己的阿里云KEYSECRET
bucket: 'kcmall-wangyihui', // 你的 OSS bucket 名称
region: 'oss-cn-hangzhou', // bucket 所在地址,我的是 华东2 杭州
cname:true, // 开启自定义域名上传
endpoint:"kcmall-wangyihui.oss-cn-hangzhou.aliyuncs.com" // 自己的域名
});
export default {
data () {
return {
visible: false,
dataForm: {
id: 0,
upwd: '',
uname: '',
classid: ''
},
imageUrl: '' ,
dataRule: {
upwd: [
{ required: true, message: '不能为空', trigger: 'blur' }
],
uname: [
{ required: true, message: '不能为空', trigger: 'blur' }
],
classid: [
{ required: true, message: '不能为空', trigger: 'blur' }
]
}
}
},
methods: {
//图片上传成功回调
handleAvatarSuccess(res) {
if (res) this.imageUrl = res.url
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
async fnUploadRequest(options) {
try {
let file = options.file; // 拿到 file
let fileName = file.name.substr(0,file.name.lastIndexOf('.'))
let date = new Date().getTime()
let fileNames = `${date}_${fileName}` // 拼接文件名,保证唯一,这里使用时间戳+原文件名
// 上传文件,这里是上传到OSS的 uploads文件夹下
client.put("headerimages/"+fileNames, file).then(res=>{
if (res.res.statusCode === 200) {
options.onSuccess(res)
}else {
options.onError("上传失败")
}
})
}catch (e) {
options.onError("上传失败")
}
},
init (id) {
this.dataForm.id = id || 0
this.visible = true
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
if (this.dataForm.id) {
this.$http({
url: this.$http.adornUrl(`/study/student/info/${this.dataForm.id}`),
method: 'get',
params: this.$http.adornParams()
}).then(({data}) => {
if (data && data.code === 200) {
this.dataForm.upwd = data.student.upwd
this.dataForm.uname = data.student.uname
this.dataForm.classid = data.student.classid
this.dataForm.header = data.student.header
}
})
}
})
},
// 表单提交
dataFormSubmit () {
this.$refs['dataForm'].validate((valid) => {
if (valid) {
this.$http({
url: this.$http.adornUrl(`/study/student/${!this.dataForm.id ? 'save' : 'update'}`),
method: 'post',
data: this.$http.adornData({
'id': this.dataForm.id || undefined,
'upwd': this.dataForm.upwd,
'uname': this.dataForm.uname,
'classid': this.dataForm.classid,
'header': this.imageUrl
})
}).then(({data}) => {
if (data && data.code === 200) {
this.$message({
message: '操作成功',
type: 'success',
duration: 1500,
onClose: () => {
this.visible = false
this.$emit('refreshDataList')
}
})
} else {
this.$message.error(data.msg)
}
})
}
})
}
}
}
</script>
controller
package com.wang.study.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.study.dao.StudentDao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.*;
import com.wang.study.entity.StudentEntity;
import com.wang.study.service.StudentService;
import com.wang.common.utils.PageUtils;
import com.wang.common.utils.R;
/**
*
*
* @author wangyihui
* @email 2195167808@163.com
* @date 2021-10-22 22:00:50
*/
@RestController
@RequestMapping("study/student")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private StudentDao studentDao;
/**
* 列表
*/
@GetMapping("/list")
//@RequiresPermissions("study:student:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils pageUtils = studentService.queryPage(params);
return R.ok().put("page", pageUtils);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("study:student:info")
public R info(@PathVariable("id") Integer id){
StudentEntity student = studentService.getById(id);
return R.ok().put("student", student);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("study:student:save")
public R save(@RequestBody StudentEntity student){
studentService.save(student);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("study:student:update")
public R update(@RequestBody StudentEntity student){
studentService.updateById(student);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("study:student:delete")
public R delete(@RequestBody Integer[] ids){
studentService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
这里用了分页插件
service impl
@Service("studentService")
public class StudentServiceImpl extends ServiceImpl<StudentDao, StudentEntity> implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public PageUtils queryPage(Map<String, Object> params) {
/**
* 前端传的当前页、每页条数、查询参数
*/
int p = Integer.parseInt(params.get("page")+"");
int limit = Integer.parseInt(params.get("limit")+"");
String key = params.get("key")+"";
QueryWrapper<StudentEntity> queryWrapper = new QueryWrapper<>();
if(key != null && !("").equals(key)){
/**
* 带条件查询时,并且不是从第一页开始查询,默认带条件查询时从第一页查询
*/
queryWrapper.like("uname",key);
p = 1;
}
Page<StudentEntity> page = new Page<>(p,limit);
Page<StudentEntity> result = studentDao.selectPage(page,queryWrapper);
return new PageUtils(result);
}
}
返回类,分页类
package com.wang.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
/**
* 返回数据
* R 继承了 HashMap 则不能继续使用泛型数据了 必须全是hashMap数据
*/
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
/**
* @param key 获取指定key的名字
*/
public <T> T getData(String key, TypeReference<T> typeReference){
// get("data") 默认是map类型 所以再由map转成string再转json
Object data = get(key);
return JSON.parseObject(JSON.toJSONString(data), typeReference);
}
/**
* 复杂类型转换 TypeReference
*/
public <T> T getData(TypeReference<T> typeReference){
// get("data") 默认是map类型 所以再由map转成string再转json
Object data = get("data");
return JSON.parseObject(JSON.toJSONString(data), typeReference);
}
public R setData(Object data){
put("data", data);
return this;
}
public R() {
put("code", 200);
put("msg", "success");
}
public static R error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系FIRENAY");
}
public static R error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map<String, Object> map) {
R r = new R();
r.putAll(map);
return r;
}
public static R ok() {
return new R();
}
public R put(String key, Object value) {
super.put(key, value);
return this;
}
public Integer getCode() {
return (Integer) this.get("code");
}
public String reponse(){
return JSON.toJSONString(this);
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.wang.common.utils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总记录数
*/
private int totalCount;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
/**
* 当前页数
*/
private int currPage;
/**
* 列表数据
*/
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
System.out.println("23456");
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
/**
* 分页
*/
public PageUtils() {
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}