效果图1:
效果图2:新增页面
效果图3:修改页面
首先引入依赖:
<!-- Oss需要的jar包-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
在后台定义一个控制器:
package com.ff.controller;
import com.aliyun.oss.OSSClient;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
// 阿里云oss上传文件相关属性值
// 阿里云API的外网域名
public static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
// 阿里云API的密钥
public static final String ACCESS_KEY_ID = "LTAI4Fzm3c6EmUexCHLvZNcm";
// 阿里云API的密钥Access Key Secret
public static final String ACCESS_KEY_SECRET = "b8OrjTpYWW3sZSlimy4sxr2WJuNX09";
// 阿里云API的bucket名称
public static final String BACKET_NAME = "jjjqqq";
// 阿里云API的文件夹名称
public static final String FOLDER = "photo/";
public static final String URl = "https://jjjqqq.oss-cn-beijing.aliyuncs.com/";
//图片上传
@RequestMapping("uploadPhoto")
public Map<String,Object> uploadPhoto(MultipartFile file) {
Map<String,Object>map=new HashMap<>();
OSSClient ossClient = null;
InputStream inputStream = null;
try {
ossClient = new OSSClient(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
//获取文件名
String filename = file.getOriginalFilename();
//截取后缀
String suffx = filename.substring(filename.lastIndexOf("."));
//获取文件名称
String newFileName= UUID.randomUUID()+suffx;
inputStream = file.getInputStream();
ossClient.putObject(BACKET_NAME,FOLDER+newFileName,inputStream);
map.put("filePath",URl+FOLDER+newFileName);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(ossClient!=null){
ossClient.shutdown();
}
}
return map;
}
}
App.Vue页面:
<template>
<div id="app">
<!--操作按钮-->
<el-button type="primary" round @click="openAdd" icon="el-icon-circle-plus-outline"> 新增</el-button>
<el-button type="danger" round icon="el-icon-delete" @click="openAelete(multipleSelection)" :disabled="this.multipleSelection.length === 0">批量删除</el-button>
<!--
查询数据列表
-->
<el-table ref="multipleTable" :data="tableData" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" v-show="tableData.length>0">
<el-table-column type="selection" width="55" fixed label="#"></el-table-column>
<el-table-column fixed prop="id" label="序号" >
<!--如果想要对当前字段进行转换,需要用到template-->
<template slot-scope="scope">{{scope.$index+1}}</template>
</el-table-column>
<!--图片展示-->
<el-table-column prop="photo" label="图片" show-overflow-tooltip >
<template slot-scope="scope" ><img :src="scope.row.photo" width="50" ></template>
</el-table-column>
<el-table-column fixed="right" label="操作" width="100">
<template slot-scope="scope">
<el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
<el-button type="text" size="small" @click="upda(scope.row)">编辑</el-button>
</template>
</el-table-column>
</el-table>
<!--分页-->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="1"
:page-sizes="[5, 10, 15, 20]"
:page-size="5"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
<!--新增表单-->
<el-dialog title="药品数据" :visible.sync="dialogFormVisible" @close="close1('form')">
<el-form ref="form" :rules="rules" :model="form" label-width="80px" >
<el-form-item label="药品图片" prop="photo">
<el-upload
class="avatar-uploader"
action="http://localhost:8080/file/uploadPhoto"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item>
<el-button v-if="aaa" type="primary" @click="add('form')">新增</el-button>
<el-button v-if="bbb" type="primary" @click="update1('form')">修改</el-button>
<el-button @click="cancel('form')">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
</div>
</template>
<script>
export default {
name:'App',
created(){
//初始化方法
this.queryDrug();
},
data(){
return {
imageUrl:"", //插件自带图片属性
tableData:[],
//复选框默认
multipleSelection: [],
dialogFormVisible: false,
form:{
imageUrl:"", //插件自带图片属性
photo:"", //图片封装类属性
img:"" //用于删除老图片
},
total:0,
currentPage:1,
pageSize:5,
aaa:true,
bbb:false,
}
},
methods:{
//查询列表
queryDrug:function () {
var _this = this;
this.$axios.get("http://localhost:8080/drug/queryDrug?currentPage="+this.currentPage+"&pageSize="+this.pageSize).then(function (result) {
_this.tableData = result.data.list;
_this.total=result.data.total;
})
},
//新增
add(form){
var _this = this;
_this.aaa=true;
_this.bbb=false;
this.$refs[form].validate((valid) => {
if (valid) {
this.form.person=this.form.person.toString();
//this.$qs.stringify()如果$qs.stringify()方法点不出来,就安装qs命令 nqm install qs
this.$axios.post("http://localhost:8080/drug/addDrug",this.$qs.stringify(this.form)).then(function () {
_this.$message.success("新增成功")
_this.queryDrug();
_this.dialogFormVisible=false;
}).catch(function () {
_this.$message.success("新增失败")
})
} else {
return false;
}
}
)
}
,
//新增弹框
openAdd(){
this.dialogFormVisible=true;
},
//全局清空表单数据
close1(form){
this.$refs[form].resetFields()
//清空图片数据
this.imageUrl = "";
}
//弹框取消
cancel(form){
this.dialogFormVisible=false;
this.$refs[form].resetFields();
//清空图片数据
this.imageUrl = "";
},
//回显
upda(row) {
var _this = this;
_this.aaa=false;
_this.bbb=true;
//回显数据
this.form=row;
//回显图片
this.imageUrl=row.photo;
//回显图片删除老图片
this.form.img=row.photo;
//打开弹框
_this.dialogFormVisible=true;
},
//修改
update1:function (form) {
var _this = this;
this.$refs[form].validate((valid) => {
if (valid) {
this.form.person=this.form.person.toString();
//this.$qs.stringify()如果$qs.stringify()方法点不出来,就安装qs命令 nqm install qs
this.$axios.post("http://localhost:8080/drug/updateDrug",this.$qs.stringify(this.form)).then(function () {
_this.$message.success("修改成功")
_this.queryDrug();
_this.dialogFormVisible=false;
}).catch(function () {
_this.$message.success("修改失败")
})
} else {
return false;
}
}
)
},
handleAvatarSuccess(res, file) {
//新增图片
this.form.photo=res.filePath;
this.imageUrl = URL.createObjectURL(file.raw);
},
//设置图片类型和大小
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
//每页条数
handleSizeChange(val){
this.pageSize=val;
this.queryDrug();
},
//当前页
handleCurrentChange(val){
this.currentPage=val;
this.queryDrug();
},
}
}
</script>
<style>
/* 解决element-ui的table表格控件表头与内容列不对齐问题 */
.el-table th.gutter{
display: table-cell!important;
}
</style>
<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>
其中img是自己定义的,数据库没有这个字段
修改时在DrugServiceImpl层删除老图片:
@Override
@Override
public void updateDrug(Drug drug) {
//判断新图片和老图片都不为null
if(StringUtils.isNotBlank(drug.getImg()) && StringUtils.isNotBlank(drug.getPhoto()) && !drug.getImg().equals(drug.getPhoto())){
//删除老图片
OSSUtil.deleteFile(drug.getImg());
}
drugMapper.updateById(drug);
}
其中OSSUtil是自己写的工具类:
public class OSSUtil {
// 阿里云oss上传文件相关属性值
// 阿里云API的外网域名
public static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
// 阿里云API的密钥
public static final String ACCESS_KEY_ID = "LTAI4Fzm3c6EmUexCHLvZNcm";
// 阿里云API的密钥Access Key Secret
public static final String ACCESS_KEY_SECRET = "b8OrjTpYWW3sZSlimy4sxr2WJuNX09";
// 阿里云API的bucket名称
public static final String BACKET_NAME = "jjjqqq";
// 阿里云API的文件夹名称
public static final String FOLDER = "photo/";
public static final String URl = "https://jjjqqq.oss-cn-beijing.aliyuncs.com/";
public static void deleteFile(String fileName){
OSSClient ossClient = new OSSClient(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
//给fileName重新赋值
String replace = fileName.replace(URl, "");
//删除
ossClient.deleteObject(BACKET_NAME,replace);
ossClient.shutdown();
}
}