威望0
积分7946
贡献0
在线时间763 小时
UID1
注册时间2021-4-14
最后登录2024-11-21
管理员
- UID
- 1
- 威望
- 0
- 积分
- 7946
- 贡献
- 0
- 注册时间
- 2021-4-14
- 最后登录
- 2024-11-21
- 在线时间
- 763 小时
|
项目简介
开发一个基于Spring Boot + Vue的前后端分离相册管理系统项目,完成增、删、改、列表、多条件、分页的功能
功能细节:
实现照片的新增、删除、修改、列表、多条件、分页
图片上传使用 el-upload 控件,建议设置 auto-upload 为 false。
控制图片最大不能超过5M
上传的必须是图片,或者约束后缀为 png/jpg/gif/bmp等图片。
建议先保存标题信息到数据库,并返回得到noid的值,然后再上传图片,并更新 relative_path字段。
图片保存文件命名为 yyyyMMdd/HHmmssXXXX.后缀这样的图片,例如图片为 仓鼠.png,保存后类似为 20220107/1115232832.png, XXXX表示4位的随机数字。
图片在列表上显示为 200X200大小
列表要支持分页,分页控件使用 el-pagination
删除的时候,要将图片从硬盘上删除掉,然后再删除数据库中的记录。
列表页显示如下
效果图
开发环境
后端:Spring Boot + MyBatis + Maven
前端:Vue + ElementUI
工具:前端使用WebStorm,后端使用IDEA
项目风格
请求方式统一为Post请求,目的是保证安全性
规范了接口层统一返回格式为ResultBean,详细如:
统一返回格式风格类,ResultBean
状态码,详细信息,数据
数据表
t_picture
[mw_shl_code=applescript,true]CREATE TABLE `t_picture` (
`noid` int(11) NOT NULL AUTO_INCREMENT,
`picture_name` varchar(64) NOT NULL COMMENT '照片名称',
`relative_path` varchar(128) DEFAULT NULL COMMENT '存储相对路径',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`noid`)
) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8mb4
[/mw_shl_code]
项目结构
前端结构
后端结构
项目难点
前端部分难点:
上传文件采用elementui控件的el-upload,要求不可自动上传,所以设置自动上传为false
其中,要先保存数据到数据库在进行保存图片路径存入数据库,通过存入的数据id去修改当前的数据
显示图片时采用了provide / inject组合控制的显示
因为上传成功后需要再次刷新,如果不刷新,图片不出来,那就要重新刷新页面,但刷新页面对用户来说极不友好,而且时间慢,效率低,所以采用该显示方式,完美解决了二次加载的问题
介绍provide / inject组合控制的显示到底怎么用
首先在app.vue中加入如下代码
app.vue
[mw_shl_code=applescript,true]<template>
<div id="app">
<router-view v-if="isRouteAlive"/>
</div>
</template>
<script>
export default {
name: 'App',
computed: {},
watch: {},
//加入provide
provide() {
return{
//返回reload方法,该方法为全局方法
reload: this.reload,
}
},
data() {
return {
isRouteAlive:true
};
},
methods: {
//刷新页面
reload() {
this.isRouteAlive = false;
this.$nextTick(function () {
this.isRouteAlive = true;
})
}
}
};
</script>
<style>
@import '//at.alicdn.com/t/font_2048717_67mh6lqgbh.css';
</style>
[/mw_shl_code]
在要二次加载的vue文件中加入provide
执行完上传图片代码后,进行二次加载
完美解决二次加载
核心源码
前端源码
PictureList.vue
[mw_shl_code=applescript,true]<template xmlns:c="http://www.w3.org/1999/html">
<div class="box-main2 box-heigt100">
<div class="box-search">
<div>
<el-input type="text" size="mini" @keydown.native.enter="clkBtnSearch" @clear="clkBtnSearch" v-model="searchInfo.searchKey" clearable placeholder="请输入标题"></el-input>
</div>
<div class="m1">
<el-button type="primary" size="mini" @click="clkBtnSearch">搜索</el-button>
</div>
<div class="m1">
<el-button type="warning" size="mini" @click="clkBtnAdd">新增</el-button>
</div>
</div>
<div class="box-table2">
<el-table :data="picturePage.list" border style="width: 100%;">
<el-table-column type="index" label="序号" width="120"></el-table-column>
<el-table-column width="150" label="照片">
<template slot-scope="scope">
<el-image :src="src_url+scope.row.relative_path"></el-image>
</template>
</el-table-column>
<el-table-column prop="picture_name" label="标题"></el-table-column>
<el-table-column prop="strCreateTime" label="上传日期"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button type="warning" @click="clkBtnEdit(scope.row)">修改</el-button>
<el-button type="danger" @click="clkBtnDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="box-page1">
<el-pagination background :current-page="picturePage.pageNum" :page-size="picturePage.pageSize" :total="picturePage.total"
layout="total,prev,pager,next"
@current-change="chgPageNum">
</el-pagination>
</div>
<el-dialog :visible.sync="showPictureDigLog" title="新增/编辑">
<el-form label-width="120px">
<el-form-item label="标题">
<el-input type="text" size="mini" placeholder="请输入标题" v-model="picture.picture_name"></el-input>
</el-form-item>
<el-form-item label="照片">
<el-image v-if="editPicture" style="width: 200px" :src="src_url+picture.relative_path"></el-image>
<el-upload
class="upload-demo"
ref="upload"
:action="uploadUrl"
:data="uploadDataParam"
:before-upload="checkFileType"
accept=".png,.jpg,.gif, .bmp"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传png/jpg/gif/bmp文件,且不超过5M</div>
</el-upload>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button type="primary" size="mini" @click="clkBtnSave">确定</el-button>
<el-button type="warning" size="mini" @click="showPictureDigLog = false">取消</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import request from '@/common/utils/request';
export default {
computed:{
},
inject: ['reload'],
data() {
return {
searchInfo: {searchKey:''},
picturePage:{pageNum: 1, pageSize: 2, list: []},
showPictureDigLog:false,
picture:{},
uploadUrl:'',
uploadDataParam:{},
src_url:'http://127.0.0.1:8345/springbootajax/',
editPicture:false,
};
},
watch:{
'$route.path':{
handler:function(newVal){
if(newVal == '/picture-list'){
this.initData();
}
}, immediate: true
},
},
mounted() {
this.uploadUrl = this.settings.apiUrl + "/picture/upload";
this.initData();
},
methods: {
initData() {
this.getPictureList();
},
getPictureList() {
let url = this.settings.apiUrl + "/picture/page";
let data = {};
data.searchKey = this.searchInfo.searchKey;
data.pageNum = this.picturePage.pageNum;
data.pageSize = this.picturePage.pageSize;
console.log(data)
request.post(url, data).then((res) => {
if (res.code === 0) {
this.picturePage = res.data;
}
})
},
clkBtnAdd(){
this.picture = {};
this.showPictureDigLog = true;
},
clkBtnEdit(row) {
this.picture = JSON.parse(JSON.stringify(row));
this.editPicture = true;
this.showPictureDigLog = true;
},
checkFileType(file) {
let imgSize = file.size / 1024 / 1024;
console.log("文件类型:"+file.type);
console.log("文件大小:" + imgSize)
if (imgSize > 5) {
this.$message("文件超出规定上传大小,请重新上传文件!")
return false;
}
//png/jpg/gif/bmp
},
clkBtnSave() {
let url = this.settings.apiUrl + "/picture/save";
let data = this.picture;
request.post(url, data).then((res) => {
if (res.code === 0) {
this.uploadDataParam.noid = res.data;
this.submitUpload();
this.showPictureDigLog = false;
this.getPictureList();
this.$message("保存成功~")
}
})
},
//保存表单提交
submitUpload() {
this.$refs.upload.submit();
this.reload();
},
clkBtnDelete(row) {
this.$confirm("您确信要删除吗?", "提示").then(() => {
let url = this.settings.apiUrl + "/picture/delete";
let data = {noid: row.noid};
request.post(url, data).then((res) => {
if (res.code === 0) {
this.getPictureList();
this.$message("删除成功~");
}
})
}).catch(() => {
this.$message("取消删除~");
})
},
chgPageNum(pageNum) {
this.picturePage.pageNum = pageNum;
this.getPictureList();
},
clkBtnSearch() {
this.getPictureList();
}
},
};
</script>
<style lang="scss" scoped="scoped">
.box-main2 {
width: 90%;
margin: 10px;
box-table2{
height: auto;
}
.box-search{
display: flex;
margin: 10px;
.m1{
padding-left: 10px;
}
}
.box-page1{
margin-top: 10px;
}
}
</style>
[/mw_shl_code]
添加路由
route.js
[mw_shl_code=applescript,true]{
path: '/picture-list',
meta: {pageTitle: '相册管理', leftMenuIndex: 'picture-list'},
component: () => import('@/views/PictureList')
},
[/mw_shl_code]
添加左侧菜单显示
LeftMenu.vue
[mw_shl_code=applescript,true]<el-menu-item index="picture-list" @click.native="clkItem('/picture-list')">
<i class="menuitem-icon iconfont icon-logging"></i>
<span class="menuitem-text" slot="title">相册列表</span>
</el-menu-item>
[/mw_shl_code]
后端源码
PictureController
[mw_shl_code=applescript,true]package com.wanshi.controller;
import com.github.pagehelper.PageInfo;
import com.wanshi.bean.Picture;
import com.wanshi.bean.ResultBean;
import com.wanshi.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/picture")
public class PictureController {
@Autowired
private PictureService pictureService;
/**
* 相册分页
* @param param
* @return
*/
@PostMapping("/page")
public ResultBean<PageInfo<Picture>> page(@RequestBody Picture param) {
ResultBean<PageInfo<Picture>> res = pictureService.page(param);
return res;
}
/**
* 保存,将新增和修改合成了一个方法,根据id判断是新增或修改
* @param param
* @return
*/
@PostMapping("/save")
public ResultBean<Integer> insert(@RequestBody Picture param) {
ResultBean<Integer> res = pictureService.save(param);
return res;
}
/**
* 删除图片
* @param param
* @return
*/
@PostMapping("/delete")
public ResultBean<Integer> delete(@RequestBody Picture param) {
ResultBean<Integer> res = pictureService.delete(param);
return res;
}
/**
* 上传图片,与上传信息分开,改为手动上传,点击确定后,先保存数据,再保存图片相关信息至数据库
* @param map
* @param file
* @return
*/
@PostMapping("/upload")
public ResultBean<Integer> upload(@RequestParam Map<String, Object> map, MultipartFile file) {
ResultBean<Integer> res = pictureService.upload(map, file);
return res;
}
}
[/mw_shl_code]
PictureService
[mw_shl_code=applescript,true]package com.wanshi.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanshi.bean.Picture;
import com.wanshi.bean.ResultBean;
import com.wanshi.config.GlobalSet;
import com.wanshi.mapper.PictureMapper;
import com.wanshi.utils.PbFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
@Service
public class PictureService {
@Autowired
private GlobalSet globalSet;
@Autowired
private PictureMapper pictureMapper;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
public ResultBean<PageInfo<Picture>> page(Picture param) {
PageHelper.clearPage();
PageHelper.startPage(param.getPageNum(), param.getPageSize());
List<Picture> pictureList = pictureMapper.list(param);
for (Picture picture : pictureList) {
if (picture != null) {
picture.setStrCreateTime(sdf.format(picture.getCreate_time()));
}
}
PageInfo<Picture> pageInfo = new PageInfo<>(pictureList);
return ResultBean.create(0, "success", pageInfo);
}
public ResultBean<Integer> save(Picture param) {
if (param.getNoid() != null ) {
pictureMapper.update(param);
} else {
pictureMapper.insert(param);
}
return ResultBean.create(0, "success", param.getNoid());
}
public ResultBean<Integer> delete(Picture param) {
//获取要删除的照片存储相对地址
Picture picture = pictureMapper.get(param);
//拼接绝对路径并删除
new File(globalSet.getUploadPath() + picture.getRelative_path()).delete();
pictureMapper.delete(param);
return ResultBean.create(0, "success", null);
}
public ResultBean<Integer> upload(Map<String, Object> map, MultipartFile file) {
try {
//查询当前id是否存在,并上传过图片
Picture picture2 = new Picture();
picture2.setNoid(Integer.valueOf((String)map.get("noid")));
Picture picture3 = pictureMapper.get(picture2);
if (picture3.getRelative_path() != null) {
//拼接绝对路径并删除
new File(globalSet.getUploadPath() + picture3.getRelative_path()).delete();
}
//上传文件,获得上传后的文件名称
String uploadName = PbFileUtils.upload(file, globalSet.getUploadPath());
if (!StringUtils.isEmpty((String)map.get("noid"))) {
Picture picture = new Picture();
picture.setNoid((Integer.valueOf((String) map.get("noid"))));
picture.setRelative_path(uploadName);
pictureMapper.updateImg(picture);
}
} catch (Exception e) {
e.printStackTrace();
}
return ResultBean.create(0, "success", null);
}
}
[/mw_shl_code]
工具类PbFileUtils
[mw_shl_code=applescript,true]package com.wanshi.utils;
import com.wanshi.config.GlobalSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* 图片上传类
*/
public class PbFileUtils {
/**
* 文件上传,
* @param file 上传文件
* @param uploadPath 要上传到的路径
* @return
* @throws IOException
*/
public static String upload(MultipartFile file, String uploadPath) throws IOException {
String finalFileName = "";
if (file.getSize() > 0) {
String originalFilename = file.getOriginalFilename();
//获取源文件的后缀名
String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
//获取年月
SimpleDateFormat sdfYyyyMMdd = new SimpleDateFormat("yyyy-MM");
finalFileName = sdfYyyyMMdd.format(new Date()) + "/";
//获取日
SimpleDateFormat sdfdd = new SimpleDateFormat("dd");
finalFileName += sdfdd.format(new Date()) + "/";
//获取时分秒
SimpleDateFormat sdfHHmmss = new SimpleDateFormat("HHmmss");
finalFileName += sdfHHmmss.format(new Date());
//生成4位随机数字
Integer rndNum = new Random().nextInt(1000)+9000;
//拼接随机数字和后缀名
finalFileName += rndNum + extName;
//目标文件
File f1 = new File(uploadPath+finalFileName);
if (!f1.exists()) {
f1.mkdirs();
}
//开始上传
file.transferTo(f1);
}
return finalFileName;
}
}
[/mw_shl_code] |
上一篇:JS实现弹性漂浮广告代码下一篇:如何高效地在网上找开源项目?
|