效果圖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是自己定義的,資料庫沒有這個字段
@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);
}
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();
}
}