JAVA全栈CMS系统vue图片/视频上传组件,多图上传及删除功能11
ztj100 2024-11-13 14:02 17 浏览 0 评论
1.上一期文件头像上传的file表借鉴
# 12.文件资源管理表
DROP TABLE IF EXISTS `file`;
CREATE TABLE `file`(
`uni_id` CHAR(8) NOT NULL DEFAULT '' COMMENT '唯一ID',
`name` VARCHAR(100) NOT NULL COMMENT '文件名',
`path` VARCHAR(100) NOT NULL COMMENT '文件相对路径',
`module_id` CHAR(8) COMMENT '模块ID',
`user_id` CHAR(8) COMMENT '上传用户ID',
`suffix` VARCHAR(100) COMMENT '文件后缀',
`size` INT COMMENT '大小|字节B',
`content_type` VARCHAR(100) COMMENT '文件上传类型',
`type_id` int(11) NOT NULL DEFAULT '0' COMMENT '资源类型',
`use_type` CHAR(1) COMMENT '应用场景|P公共资源|I私有资源|D公司宣传资料|A公司活动资料|C公司产品资料|T其他',
`is_show` int DEFAULT '1' COMMENT '显示1 || 不显示0',
`create_time` datetime(3) DEFAULT NULL COMMENT '创建时间',
`update_time` datetime(3) DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`uni_id`),
UNIQUE KEY `path_unique` (`path`)
)ENGINE=INNODB DEFAULT charset=utf8mb4 COMMENT='文件资源管理表';
本期功能实现预览
2.更新上传文件,自动创建递归二级目录:根据use_type创建一级目录,根据日期创建二级目录
Controller更新后端递归新增目录方法
package cevent.source.cloudcenter.source.controller.admin;/**
* Created by Cevent on 2021/4/24.
*/
import cevent.source.cloudcenter.server.dto.FileDto;
import cevent.source.cloudcenter.server.dto.ResponseDataDto;
import cevent.source.cloudcenter.server.enums.UseTypeEnum;
import cevent.source.cloudcenter.server.service.FileService;
import cevent.source.cloudcenter.server.util.UUID8Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author cevent
* @description 文件上传:单图
* @date 2021/4/24 14:41
*/
@RestController
@RequestMapping("/admin")
public class UploadIconController {
private static final Logger LOG= LoggerFactory.getLogger(UploadIconController.class);
public static final String BUSINESS_NAME="文件上传模块";
@Resource
private FileService fileService;
//注入properties中的file配置
@Value("${file.targetPath}")
private String FILE_TARGET_PATH;
@Value("${file.getPath}")
private String FILE_GET_PATH;
/*1.单图上传:
@RequestParam:基于文件是formData形式传输
MultipartFile:富文本大文件
file:formData.append('file',icon),前端formData中提交file参数名,包含元素查询中的icon文件
*/
@RequestMapping("/test")
public String test(){
return "文件系统模块启动成功";
}
@RequestMapping("/upload/icon")
public ResponseDataDto uploadIcon(@RequestParam MultipartFile file,String moduleId,String useType) throws IOException {
LOG.info("上传的文件file:{}",file);
LOG.info("上传的文件file名fileName:{}",file.getOriginalFilename());
LOG.info("上传的文件file大小:{}",file.getSize());
LOG.info("上传的文件file名name:{}",file.getName());
LOG.info("上传的文件file类型:{}",file.getContentType());
//保存文件到本地
String fileName=file.getOriginalFilename();
String fileKey= UUID8Util.getShortUUID();
//获取文件后缀名(类型),全部转小写
String suffix=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
String contentType=file.getContentType();
Long size=file.getSize();
//文件名配置
Date now=new Date();
String date=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(now);
//获取枚举类型,生成新的文件夹路径
UseTypeEnum useTypeEnum=UseTypeEnum.getByCode(useType);
//获取到枚举名SOURCE("","")
String dateDir=new SimpleDateFormat("yyyy_MM_dd").format(now);
String dir=useTypeEnum.name().toLowerCase();
File fullDir=new File(FILE_TARGET_PATH+"source"+File.separator+dir+File.separator+dateDir);
LOG.info("创建的fullDir目录:{}",fullDir);
//创建文件夹
if(!fullDir.exists()){
fullDir.mkdirs();
LOG.info("创建成功目录?:{}",fullDir.mkdirs());
}
String name=date+"_"+fileKey+"_"+fileName;
//File.separator生成不同操作系统的/斜杠
String path="source/"+dir+File.separator+dateDir+File.separator+name;
LOG.info("上传的path:{}",path);
//全路径
String fullPath=FILE_TARGET_PATH+path;
//放入日期目录
File dest=new File(fullPath);
file.transferTo(dest);
LOG.info("获取destination目的位置完全路径:{}",dest.getAbsolutePath());
//保存file
FileDto fileDto=new FileDto();
fileDto.setName(name);
//返回相对路径
//fileDto.setPath(path);
//返回全路径
fileDto.setPath(FILE_GET_PATH+path);
fileDto.setSuffix(suffix);
fileDto.setContentType(contentType);
fileDto.setSize(Math.toIntExact(size));
fileDto.setUseType(useType);
fileDto.setIsShow(0);
fileDto.setModuleId(moduleId);
fileService.save(fileDto);
ResponseDataDto responseData=new ResponseDataDto();
responseData.setResponseData(fileDto);
return responseData;
}
}
文章模块更新图片上传:保存bug:pic_list为longTest类型,mybatis普通的insert无法保存该类型,需要
pageDto查询方法更新
3.前端上传视频更新fileIcon组件,引用后的接收请求格式即可
Template模块…
<el-form-item label="文章视频" prop="articleVideo">
<file-icon :upload-tile="'上传视频'" :input-id="'upload-articleVideo-icon'" :suffix-type="['mp4']"
:uniId="article.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_PUBLIC.key"
:after-upload="afterArticleVideoUpload"></file-icon>
<el-row class="upload-icon">
<el-col :span="12">
<video class="articleVideo" :src="article.articleVideo" controls="controls" ></video>
</el-col>
</el-row>
</el-form-item>
Css部分
/*视频上传*/
.articleVideo{
width: 100%;
}
4.自动获取视频时长
Template模块
<el-form-item label="文章视频" prop="articleVideo">
<file-icon :upload-tile="'上传视频'" :input-id="'upload-articleVideo-icon'" :suffix-type="['mp4']"
:uniId="article.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_PUBLIC.key"
:after-upload="afterArticleVideoUpload"></file-icon>
<el-row class="upload-icon">
<el-col :span="12">
<video id="av" class="articleVideo" :src="article.articleVideo" controls="controls" ></video>
</el-col>
</el-row>
</el-form-item>
<el-form-item label="时长" prop="videoTime">
<el-input id="videoTime" class="inputLine" v-model="article.videoTime" disabled></el-input>
</el-form-item>
视频时长转换
afterArticleVideoUpload(resp){
console.log("上传到的article视频地址:",resp.responseData);
this.article.articleVideo=resp.responseData.path;
this.getVideoTime();
console.log("这里的picList:",this.article.articleVideo);
},
//获取视频时间
getVideoTime(){
let video=document.getElementById("av");
this.article.videoTime=parseInt(video.duration,10);
console.log("videoTime转换:",this.article.videoTime);
}
5.多图上传回显,使用file表进行module关联更新
1)fileController更新,根据moduleId查询file列表
/*
根据moduleId查询文件列表
*/
@GetMapping("/list/{moduleId}")
public ResponseDataDto listByModuleId(@PathVariable String moduleId){
ResponseDataDto responseData=new ResponseDataDto();
List<FileDto> fileDtos=fileService.listByModuleId(moduleId);
responseData.setResponseData(fileDtos);
return responseData;
}
2)fileService更新实现
//7.根据传入的moduleId查询file文件列表
public List<FileDto> listByModuleId(String moduleId){
FileExample fileExample=new FileExample();
FileExample.Criteria criteria=fileExample.createCriteria();
criteria.andModuleIdEqualTo(moduleId);
List<File> files=fileMapper.selectByExample(fileExample);
return DuplicateUtil.copyList(files,FileDto.class);
}
3) article更新edit方法,进入页面之前根据moduleId查询fileList
//4.修改
edit(article) {
console.log("edit的article:", article);
/*jquery继承对象: $.extend({新对象},旧对象)
避免vue数据绑定漏洞,更改数据时,随之更改显示的data,但实际没有进行真实保存数据库
*/
this.article = $.extend({}, article);
//SessionStorage.set("article",article);
SessionStorage.set(ARTICLE_MODULE_PARENTID,this.module.parentId);
console.log("从moduleSub传入的module:",this.module);
//加载article的文件列表
Loadings.show();
this.$axios.get(process.env.VUE_APP_SERVER + '/source/admin/file/list/'+ article.uniId)
.then((response)=>{
let resp=response.data;
if(resp.success){
SessionStorage.set(FILE_LIST,resp.responseData);
console.log("缓存中的aticle-file-list:",SessionStorage.get(FILE_LIST));
Loadings.hide();
}
});
this.$router.push({
name: "business/article/add",
params: {article}
});
},
4) addArticle在mounted时,获取sessionStorage中的FILE_LIST,同步到files
mounted() {
console.log(this.message);
console.log("传入的article==>params:", this.$route.params.article);
let moduleParentId = SessionStorage.get(ARTICLE_MODULE_PARENTID) || "";
if (this.$route.params.article != null) {
this.article = this.$route.params.article;
this.article.moduleUniId = moduleParentId;
//2.获取当前article的富文本内容
$("#content").summernote('code', this.article.articleContent);
//缓存中的文件列表
this.files= SessionStorage.get(FILE_LIST);
console.log("传入的FILE_LIST:",this.files);
console.log("article传入的moduleParentId:", moduleParentId);
let optionArticle = document.getElementById("optionArticle");
let submitBtn = document.getElementById("submitBtn");
optionArticle.innerHTML = '更新文章数据';
submitBtn.innerHTML = "立即更新";
} else {
//获取article在session中保存的articleModuleId
let moduleId = SessionStorage.get(ARTICLE_MODULE_ID) || "";
console.log("article传入的moduleId缓存session数据:", moduleId);
if (moduleId !== null) {
this.article = {};
this.article.moduleId = moduleId;
this.article.moduleUniId = moduleParentId;
}
}
//富文本
$("#content").summernote({
focus: true,
height: 300
})
},
5) addArticle在上传picList时,更新files中的图片列表,再次写入缓存setSession,并调用savePicList方法,将files中的path保存到picList
//接收文件上传组件传入的resp
afterUpload(resp) {
if (resp.success) {
console.log("上传到的article图片列表地址:", resp.responseData);
this.article.picList = resp.responseData.path;
console.log("这里的picList:", this.article.picList);
this.getFiles();
}
},
getFiles(){
this.$axios.get(process.env.VUE_APP_SERVER + '/source/admin/file/list/'+ this.article.uniId)
.then((response)=>{
let resp=response.data;
if(resp.success){
this.files=resp.responseData;
this.savePicList(this.files);
SessionStorage.set(FILE_LIST,this.files);
}
});
},
//存入picList
savePicList(files){
let pics=[];
for(let i=0;i<files.length;i++){
pics.push(files[i].path);
this.article.picList=JSON.stringify(pics);
}
console.log("存入的picList:",this.article.picList);
},
6)addArticle在删除时,调用tools中的删除数组对象方removeObj(array,file),再次调用getFiles更新picList
//删除文件
delFile(file){
let _this = this;
let fileParam =file;
toast.showConfirm(file.name, function () {
_this.$axios.delete(process.env.VUE_APP_SERVER + '/source/admin/file/del/' + fileParam.uniId)
.then((response) => {
let resp = response.data;
if (resp.success) {
console.log("删除的模块-文件资源:", file.path);
_this.getFiles();
Tool.removeObj(_this.files,file);
console.log("files删除成功了吗?",Tool.removeObj(_this.files,file));
//_this.pageList(1);
}
})
})
},
gitee提交,源码开放,长期维护,欢迎fork,关注,mark,点赞,收藏,转发
gitee地址:
https://gitee.com/cevent_OS/yameng-cevent-source-cloudcenter.git
相关推荐
- WPS 隐藏黑科技!OCT2HEX 函数用法全攻略,数据转换不再愁
-
WPS隐藏黑科技!OCT2HEX函数用法全攻略,数据转换不再愁在WPS表格的强大函数库中,OCT2HEX函数堪称数据进制转换的“魔法钥匙”。无论是程序员处理代码数据,还是工程师进行电路设计...
- WPS 表格隐藏神器!LEFTB 函数让文本处理更高效
-
WPS表格隐藏神器!LEFTB函数让文本处理更高效在职场办公和日常数据处理中,WPS表格堪称我们的得力助手,而其中丰富多样的函数更是提升效率的关键。今天,要为大家介绍一个“宝藏函数”——LEF...
- Java lombok 使用教程(lombok.jar idea)
-
简介Lombok是...
- PART 48: 万能结果自定义,SWITCH函数!
-
公式解析SWITCH:根据值列表计算表达式并返回与第一个匹配值对应的结果。如果没有匹配项,则返回可选默认值用法解析1:评级=SWITCH(TRUE,C2>=90,"优秀",C2...
- Excel 必备if函数使用方法详解(excel表if函数使用)
-
excel表格if函数使用方法介绍打开Excel,在想输出数据的单元格点击工具栏上的“公式”--“插入函数”--“IF”,然后点击确定。...
- Jetty使用场景(jetty入门)
-
Jetty作为一款高性能、轻量级的嵌入式Web服务器和Servlet容器,其核心优势在于模块化设计、快速启动、低资源消耗...
- 【Java教程】基础语法到高级特性(java语言高级特性)
-
Java作为一门面向对象的编程语言,拥有清晰规范的语法体系。本文将系统性地介绍Java的核心语法特性,帮助开发者全面掌握Java编程基础。...
- WPS里这个EVEN 函数,90%的人都没用过!
-
一、开篇引入在日常工作中,我们常常会与各种数据打交道。比如,在统计员工绩效时,需要对绩效分数进行一系列处理;在计算销售数据时,可能要对销售额进行特定的运算。这些看似简单的数据处理任务,实则隐藏着许多技...
- 64 AI助力Excel,查函数查用法简单方便
-
在excel表格当中接入ai之后会是一种什么样的使用体验?今天就跟大家一起来分享一下小程序商店的下一步重大的版本更新。下一个版本将会加入ai功能,接下来会跟大家演示一下基础的用法。ai功能规划的是有三...
- python入门到脱坑 函数—函数的调用
-
Python函数调用详解函数调用是Python编程中最基础也是最重要的操作之一。下面我将详细介绍Python中函数调用的各种方式和注意事项。...
- 从简到繁,一文说清vlookup函数的常见用法
-
VLOOKUP函数是Excel中常用的查找与引用函数,用于在表格中按列查找数据。本文将从简单到复杂,逐步讲解VLOOKUP的用法、语法、应用场景及注意事项。一、VLOOKUP基础:快速入门1.什么是...
- Java新特性:Lambda表达式(java lambda表达式的3种简写方式)
-
1、Lambda表达式概述1.1、Lambda表达式的简介Lambda表达式(Lambdaexpression),也可称为闭包(Closure),是Java(SE)8中一个重要的新特性。Lam...
- WPS 冷门却超实用!ODD 函数用法大揭秘,轻松解决数据处理难题
-
WPS冷门却超实用!ODD函数用法大揭秘,轻松解决数据处理难题在WPS表格庞大的函数家族里,有一些函数虽然不像SUM、VLOOKUP那样广为人知,却在特定场景下能发挥出令人惊叹的作用,OD...
- Python 函数式编程的 8 大核心技巧,不允许你还不会
-
函数式编程是一种强调使用纯函数、避免共享状态和可变数据的编程范式。Python虽然不是纯函数式语言,但提供了丰富的函数式编程特性。以下是Python函数式编程的8个核心技巧:...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)