当前位置: 首页 > news >正文

项目总结知识点记录-文件上传下载(三)

 

(1)文件上传

 

 代码:

 @RequestMapping(value = "doUpload", method = RequestMethod.POST)public String doUpload(@ModelAttribute BookHelper bookHelper, Model model, HttpSession session) throws IllegalStateException, IOException, ParseException {logger.info("you are uploading a book! ");logger.info("This book is " + bookHelper.getTitle() + "!");String fileName = bookHelper.getBookFile().getOriginalFilename();String bookCover = bookHelper.getBookCover().getOriginalFilename();MultipartFile bookFile = bookHelper.getBookFile();MultipartFile coverFile = bookHelper.getBookCover();if (bookFile.isEmpty()) {logger.info("Uploading failed! The book you are uploading is empty!");return "upload_failed";} else if (coverFile.isEmpty()) {logger.info("Uploading failed! The book cover you are uploading is empty!");return "upload_failed";} else {String typeId = "" + bookHelper.getLargeType() + bookHelper.getSmallType();int type_id = Integer.parseInt(typeId);String format = fileName.substring(fileName.lastIndexOf('.') + 1);List<String> typeNames;typeNames = bookService.getTypeNames(type_id);String filePath_pre = (String) PropertyConfigurer.getProperty("book_path");String filePath = filePath_pre + typeNames.get(0) +"/" + typeNames.get(1) + "/" +bookHelper.getTitle() + "." + format;File localBookFile = new File(filePath);if (localBookFile.exists()) {logger.info("Uploading failed! The book is existed!");return "upload_failed2";}bookFile.transferTo(localBookFile);String coverPath_pre = (String) PropertyConfigurer.getProperty("book_cover_path");String coverPath = coverPath_pre + typeNames.get(0) +"/" + typeNames.get(1) + "/" +bookHelper.getTitle() + ".jpg";File localCoverFile = new File(coverPath);coverFile.transferTo(localCoverFile);logger.info("The book has uploaded to local path successfully!");Book book = new Book();book.setBook_title(bookHelper.getTitle());book.setBook_author(bookHelper.getAuthor());SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");Date date = dateFormat.parse(bookHelper.getPubYear());book.setBook_pubYear(date);book.setBook_summary(bookHelper.getSummary());book.setType_id(type_id);book.setBook_format(format);book.setDownload_times(0);book.setBook_file(filePath);book.setBook_cover(coverPath);dateFormat = new SimpleDateFormat("yyMMdd", Locale.CHINESE);String pubDate = dateFormat.format(date);String upDate = dateFormat.format(new Date());int random = new Random().nextInt(900) + 100;String idStr = "" + typeId + pubDate + upDate + random;long bookID = Long.parseLong(idStr);logger.info("The book id you uploaded is " + bookID);book.setId(bookID);bookService.uploadBook(book);UserHelper userHelper = (UserHelper) session.getAttribute("userHelper");bookService.updateRecords(userHelper.getId(), bookID);userService.updateUserContribution(2, userHelper.getId());model.addAttribute("bookID", bookID);logger.info("you are coming to the uploading successful page!");return "upload_success";}}
public List<String> getTypeNames(int id) {BookType bookType;bookType = bookTypeDao.queryById(id);List<String> typeNames = new ArrayList<String>();typeNames.add(bookType.getLarge_type_name());typeNames.add(bookType.getSmall_type_name());return typeNames;}

 

前端代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head><meta><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link type="text/css" rel="stylesheet"href="${pageContext.request.contextPath }/resources/css/bootstrap.min.css" /><link type="text/css" rel="stylesheet"href="${pageContext.request.contextPath }/resources/css/bootstrap-datetimepicker.min.css" /><link type="text/css" rel="stylesheet"href="${pageContext.request.contextPath }/resources/css/upload.css" /><title>敛书网 - 文件上传</title>
</head>
<body>
<%@include file="common/loginHead.jsp"%><%@include file="common/userHead.jsp"%><div id="upload" class="container"><br><div class="row"><div class="col-md-12 "><div class="panel panel-info"><div class="panel-heading"><span class="h5 text-success">上传文件</span></div><div class="panel-body"><div id="myAlert" class="alert alert-warning hide"><a href="#" class="close" data-dismiss="alert">&times;</a><span id="form-tips" class="text-danger col-md-offset-1"></span></div><form id="uploadForm" class="form-horizontal" action="doUpload"enctype="multipart/form-data" method="POST" onsubmit="return checkUploadForm();"><div class="form-group"><label for="title" class="control-label col-md-1 text-danger">标题</label><div class="col-md-3"><input id="title" name="title" class="form-control" type="text"placeholder="请填写书籍名称"></div><label for="author" class="control-label col-md-1 text-warning">作者</label><div class="col-md-3"><input id="author" name="author" class="form-control" type="text"placeholder="请填写作者姓名,杂志填无"></div></div><div class="form-group"><label for="pubYear" class="control-label col-md-1">年月</label><div class="col-md-3"><input id="pubYear" name="pubYear" class="form-control datetimepicker"placeholder="&nbsp;&nbsp;请选择出版年月"></div><label class="control-label col-md-1">类别</label><div class="col-md-2"><select id="largeType" name="largeType" class="form-control"><option value="1">经典文学</option><option value="2">通俗小说</option><option value="3">计算机类</option><option value="4">杂志期刊</option></select></div><div class="col-md-2"><select id="smallType" name="smallType" class="form-control"></select></div></div><div class="form-group"><label for="summary" class="control-label col-md-1 text-info">简介</label><div class="col-md-6"><textarea id="summary" name="summary" class="form-control" rows="2"></textarea></div></div><div class="form-group"><label for="fileUpload" class="control-label col-md-1 text-success">文件</label><div class="input-group col-md-5"><input id="fileInfo" class="form-control" readonly type="text"placeholder="支持txt,epub,mobi和pdf格式"><span class="input-group-addon btn btn-success btn-file">Browse <input id="fileUpload" name="bookFile" type="file"></span></div></div><div class="form-group"><label for="imageUpload" class="control-label col-md-1 text-success">封面</label><div class="input-group col-md-5"><input id="imageInfo" class="form-control" readonly type="text"placeholder="支持jpg和png图片格式"><span class="input-group-addon btn btn-success btn-file">Browse <input id="imageUpload" name="bookCover" type="file"></span></div></div><br><div class="form-group"><div class="col-lg-4 col-md-offset-3"><button id="submitBtn" class="btn btn-primary" type="submit" onclick="">提交</button><button class="btn btn-info col-md-offset-2" type="reset">重置</button></div></div></form></div></div></div></div></div><hr><footer><p class="text-center">&copy; 2023</p>
</footer><script src="${pageContext.request.contextPath}/resources/js/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/jquery.cookie.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/bootstrap-datetimepicker.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/userLogin.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/userRegister.js"></script>
<script src="${pageContext.request.contextPath}/resources/js/upload.js"></script>
<script>function checkUploadForm() {var title = $('#upload #title').val();var author = $('#upload #author').val();var pubYear = $('#upload #pubYear').val();var summary = $('#upload #summary').val();var fileInfo = $('#fileInfo').val();var imageInfo = $('#imageInfo').val();var $formTip = $('#myAlert #form-tips');var fileArr = ["txt","epub","mobi","pdf"];var imageArr = ["jpg","png"];var $alert = $('#myAlert');if (title.length == 0) {$formTip.html("标题不能为空!");$alert.removeClass('hide');$('#upload #title').focus();return false;} else if(author.length == 0) {$formTip.html("作者不能为空!");$alert.removeClass('hide');$('#upload #author').focus();return false;} else if (pubYear.length == 0) {$formTip.html("出版时间不能为空!");$alert.removeClass('hide');$('#upload #pubYear').focus();return false;} else if (summary.length == 0) {$formTip.html("简介不能为空!");$alert.removeClass('hide');$('#upload #summary').focus();return false;} else if (fileInfo.length == 0) {$formTip.html("请选择书籍文件!");$alert.removeClass('hide');return false;} else if ($.inArray(getFileFormat(fileInfo),fileArr) == -1) {console.log(getFileFormat(fileInfo));$formTip.html("不支持该书籍文件!");$alert.removeClass('hide');return false;} else if (imageInfo.length == 0) {$formTip.html("请选择书籍封面!");$alert.removeClass('hide');return false;} else if ($.inArray(getFileFormat(imageInfo),imageArr) == -1) {console.log(getFileFormat(fileInfo));$formTip.html("封面格式错误,请重新上传");$alert.removeClass('hide');return false;} else {$formTip.html("正在上传...");$alert.removeClass('hide');return true;}}function getFileFormat(fileName) {return fileFormat = fileName.substring(fileName.lastIndexOf('.') + 1);}</script>
</body>
</html>

(2)文件下载

http://localhost:8888/ebooknet_war_exploded/book_download?bookID=12211101211103496&filePath=E:/lianshu/ebooks/%E7%BB%8F%E5%85%B8%E6%96%87%E5%AD%A6/%E5%8F%A4%E5%85%B8%E6%96%87%E5%AD%A6/%E5%AD%9F%E5%AD%90.txt

 

@RequestMapping(value = "/book_download")public void getBookDownload(long bookID, String filePath, HttpServletResponse response) {response.setContentType("text/html;charset=utf-8");String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);BufferedInputStream bis = null;BufferedOutputStream bos = null;try {long fileLength = new File(filePath).length();response.setContentType("application/x-msdownload");response.setHeader("Content-disposition", "attachment; filename="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));response.setHeader("Content-Length", String.valueOf(fileLength));bis = new BufferedInputStream(new FileInputStream(filePath));bos = new BufferedOutputStream(response.getOutputStream());byte[] buff = new byte[2018];int bytesRead;while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}} catch (IOException e) {e.printStackTrace();} finally {try {if (bis != null) {bis.close();}if (bos != null) {bos.close();}} catch (IOException e) {e.printStackTrace();}bookService.addDownloadTimes(bookID);logger.info("you are downloading the book, the book file is " + fileName);}}

(3)修改头像

 

 

@RequestMapping(value = "/infoModify")public String infoModify(String name, String email, String avatarImg, HttpSession session) {logger.info("The user is modifying his information!");UserHelper userHelper = (UserHelper) session.getAttribute("userHelper");User user = new User();user.setId(userHelper.getId());user.setUserName(name);user.setEmail(email);int avatarId = userService.getAvatarId(avatarImg);//根据头像存储地址获取头像的编号user.setAvatarNum(avatarId);userService.updateUserInfo(user);User user1;user1 = userService.queryById(userHelper.getId());//获取新的用户信息UserHelper newUserHelper;newUserHelper = userService.getLoginUser(user1.getUserCode(), user1.getUserPassword());session.setAttribute("userHelper", newUserHelper);//重新存入Sessionreturn "redirect:/person";}

 

 

 

 

 

 

相关文章:

项目总结知识点记录-文件上传下载(三)

&#xff08;1&#xff09;文件上传 代码&#xff1a; RequestMapping(value "doUpload", method RequestMethod.POST)public String doUpload(ModelAttribute BookHelper bookHelper, Model model, HttpSession session) throws IllegalStateException, IOExcepti…...

基于LinuxC语言实现的TCP多线程/进程服务器

多进程并发服务器 设计流程 框架一&#xff08;使用信号回收僵尸进程&#xff09; void handler(int sig) {while(waitpid(-1, NULL, WNOHANG) > 0); }int main() {//回收僵尸进程siganl(17, handler);//创建服务器监听套接字 serverserver socket();//给服务器地址信息…...

浅谈JVM垃圾回收机制

一、HotSpot VM中的GC分为两大类 1.部分收集(Partial GC): 新生代收集(Minor GC/Young GC):只对新生代进行垃圾收集老年代收集(Major GC/Old GC):只队老年代进行垃圾收集混合收集(Mixed GC):对整个新生代和老年代进行垃圾收集 2.整堆收集(Full GC) 收集整个Java堆和方法区 …...

【80天学习完《深入理解计算机系统》】第十二天3.6数组和结构体

专注 效率 记忆 预习 笔记 复习 做题 欢迎观看我的博客&#xff0c;如有问题交流&#xff0c;欢迎评论区留言&#xff0c;一定尽快回复&#xff01;&#xff08;大家可以去看我的专栏&#xff0c;是所有文章的目录&#xff09;   文章字体风格&#xff1a; 红色文字表示&#…...

基于Python+OpenCV智能答题卡识别系统——深度学习和图像识别算法应用(含Python全部工程源码)+训练与测试数据集

目录 前言总体设计系统整体结构图系统流程图 运行环境Python 环境PyCharm安装OpenCV环境 模块实现1. 信息识别2. Excel导出模块3. 图形用户界面模块4. 手写识别模块 系统测试1. 系统识别准确率2. 系统识别应用 工程源代码下载其它资料下载 前言 本项目基于Python和OpenCV图像处…...

Redis集群操作-----主从互换

一、将节点cluster1的主节点7000端口的redis关掉 [rootredis-cluster1 src]# ps -ef |grep redis 二、查看集群信息&#xff1a;...

肖sir __linux命令拓展__05

linux命令拓展 1.追加内容到某文件 echo “i like learn linux” >>quzhi.txt 2.删除指定的空目录&#xff1a; rmdir 目录名 rmdir -p 目录名 &#xff08;删除指定的空目录及其内子空目录&#xff09; 3.显示zip包信息 zipinfo 压缩包名 &#xff08;显示压缩包内的文…...

大白菜清理电脑密码教程

首先安装大白菜&#xff1a; 插入u盘一键制作启动盘 制作成功&#xff0c;重启进入u盘启动模式...

[libglog][FFmpeg] 如何把 ffmpeg 的库日志输出到 libglog里

ffmpeg 提供了自己的 log 模块 av_log&#xff0c;会默认把输出打印到 stderr 上&#xff0c;因此无法方便地跟踪日志。但是 ffmpeg 提供了一个接口 av_log_set_callback 以供外界自定义自己的日志输出。 libglog 提供的是c 形式的日志输出样式&#xff0c;因此需要将二者关联起…...

【Unity-Cinemachine相机】虚拟相机(Virtual Camera)的本质与基本属性

我们可以在游戏进行时修改各个属性&#xff0c;但在概念上&#xff0c;最好将Virtual Camera 当作一种相机行为的“配置文件”&#xff0c;而不是一个组件。 我们的相机有几种行为就为它准备几种虚拟相机&#xff0c;比如角色移动就为它第三人称相机&#xff0c;瞄准就准备一个…...

LeetCode:718. 最长重复子数组 - Python

718. 最长重复子数组 问题描述&#xff1a; 给两个整数数组 nums1 和 nums2 &#xff0c;返回 两个数组中 公共的 、长度最长 的 子数组 的 长度 。 示例 1&#xff1a; 输入&#xff1a;nums1 [1,2,3,2,1], nums2 [3,2,1,4,7] 输出&#xff1a;3 解释&#xff1a;长度最长…...

【面试题精讲】Redis如何实现分布式锁

首发博客地址 系列文章地址 Redis 可以使用分布式锁来实现多个进程或多个线程之间的并发控制&#xff0c;以确保在给定时间内只有一个进程或线程可以访问临界资源。以下是一种使用 Redis 实现分布式锁的常见方法&#xff1a; 获取锁&#xff1a; 客户端尝试使用 SETNX命令在 Re…...

list【2】模拟实现(含迭代器实现超详解哦)

模拟实现list 引言&#xff08;实现概述&#xff09;list迭代器实现默认成员函数operator* 与 operator->operator 与 operator--operator 与 operator!迭代器实现概览 list主要接口实现默认成员函数构造函数析构函数赋值重载 迭代器容量元素访问数据修改inserterasepush_ba…...

Nginx+Tomcat的动静分离与负载均衡

目录 前言 一、案例 二、Nginx的高级用法 三、tomcat部署 四、Nginx部署 五、测试 总结 前言 通常情况下&#xff0c;一个 Tomcat 站点由于可能出现单点故障及无法应付过多客户复杂多样的请求等情况&#xff0c;不能单独应用于生产环境下&#xff0c;所以我们需要一套更…...

【设计模式】Head First 设计模式——策略模式 C++实现

设计模式最大的作用就是在变化和稳定中间寻找隔离点&#xff0c;然后分离它们&#xff0c;从而管理变化。将变化像小兔子一样关到笼子里&#xff0c;让它在笼子里随便跳&#xff0c;而不至于跳出来把你整个房间给污染掉。 设计思想 将行为想象为一族算法&#xff0c;定义算法族…...

c#object类中方法的使用

C#中的Object类是所有类的基类&#xff0c;它定义了一些通用的方法和属性&#xff0c;可以在任何对象上使用。以下是Object类中常用的方法和属性的使用&#xff1a; 1.ToString()&#xff1a;将对象转换为字符串表示形式。 string str obj.ToString();2.Equals()&#xff1a;…...

三种常用盒子布局的方法

在Vue中&#xff0c;可以使用各种CSS布局属性和技巧来设置盒子的布局。以下是一些常用的方法&#xff1a; 1.使用Flexbox布局&#xff1a;在包含盒子的父元素上设置display: flex&#xff0c;然后可以使用flex-direction、justify-content和align-items 等属性来控制盒子的布局…...

GB28181学习(二)——注册与注销

概念 使用REGISTER方法进行注册和注销&#xff1b;注册和注销应进行认证&#xff0c;认证方式应支持数字摘要认证方式&#xff0c;高安全级别的宜支持数字证书认证&#xff1b;注册成后&#xff0c;SIP代理在注册过期时间到来之前&#xff0c;应向注册服务器进行刷新注册&…...

【Linux】线程安全-信号量

文章目录 信号量原理信号量保证同步和互斥的原理探究信号量相关函数初始化信号量函数等待信号量函数释放信号量函数销毁信号量函数 信号量实现生产者消费者模型 信号量原理 信号量的原理&#xff1a;资源计数器 PCB等待队列 函数接口 资源计数器&#xff1a;对共享资源的计…...

数字IC验证——PSS可移植测试用例

PSS是Accellera组织定义的测试用例生成规范&#xff0c;其思想是定义一个抽象模型&#xff0c;EDA工具可以从中生成适用于每个设计层次结构和每个验证平台的测试&#xff0c;即PSS定义了统一的测试场景&#xff0c;而场景的使用可以横跨不同验证层次和配置。 这种特性决定了PSS…...

java设计模式---策略模式

策略模式的定义 策略设计模式是一种行为设计模式。当在处理一个业务时&#xff0c;有多种处理方式&#xff0c;并且需要再运行时决定使哪一种具体实现时&#xff0c;就会使用策略模式。 策略模式的类图&#xff1a; 策略模式的实现 在支付业务中&#xff0c;有三种付款方式&…...

5-redis集群搭建安装

1.先决条件 1.1.OS基础配置 CentOS为了能够正常安装redis,需要对CentOS进行常规的一些基础配置,主要有:关闭防火墙与selinux,设置主机名,配置虚拟机IP地址使其能够与外网ping通,配置IP地址与主机名映射,配置yum源。具体配置参见: Linux常规基础配置_小黑要上天的博客…...

(数字图像处理MATLAB+Python)第十一章图像描述与分析-第七、八节:纹理描述和其他描述

文章目录 一&#xff1a;纹理描述&#xff08;1&#xff09;联合概率矩阵法A&#xff1a;定义B&#xff1a;基于联合概率矩阵的特征C&#xff1a;程序 &#xff08;2&#xff09;灰度差分统计法A&#xff1a;定义B&#xff1a;描述图像特征的参数 &#xff08;3&#xff09;行程…...

MySQL提权

参考&#xff1a; mysql提权篇 | Wh0ales Blog MySQL 提权方法整理 - Geekbys Blog MySQL_UDF提权漏洞复现-云社区-华为云 MYSQL UDF手动提权及自动化工具使用_udf提权工具_小直789的博客-CSDN博客 MySQL提权的三种方法 - FreeBuf网络安全行业门户 ......

FPGA优质开源项目 – UDP万兆光纤以太网通信

本文开源一个FPGA项目&#xff1a;UDP万兆光通信。该项目实现了万兆光纤以太网数据回环传输功能。Vivado工程代码结构和之前开源的《UDP RGMII千兆以太网》类似&#xff0c;只不过万兆以太网是调用了Xilinx的10G Ethernet Subsystem IP核实现。 下面围绕该IP核的使用、用户接口…...

如何中mac上安装多版本python并配置PATH

摘要 mac 默认安装的python是 python3&#xff0c;但是如果我们需要其他python版本时&#xff0c;该怎么办呢&#xff1f; 例如&#xff1a;需要python2 版本&#xff0c;如果使用homebrew安装会提示没有python2。同时使用python --version 会发现commond not found。 所以本…...

window 常用基础命令

0、起步 0-1) 获取命令的参数指引 netstat /? 0-2) 关于两个斜杠&#xff1a; window 文件路径中使用反斜杠&#xff1a;\ linux 文件路径中使用&#xff1a;/ 1、开关机类指令 shutdown /s # 关机shutdown /r # 重启shutdown /l …...

lintcode 1815 · 警报器 【simple vip 前缀和数组】

题目 https://www.lintcode.com/problem/1815 一个烟雾警报器会监测len秒内的烟雾值&#xff0c;如果这段时间烟雾值平均值大于k那么警报器会报警。现在给你n个数代表刚开始工作n秒内警报器监测的烟雾值&#xff08;警报器从第len秒开始判断是否报警&#xff09;&#xff0c;…...

【强化学习】MDP马尔科夫链

基本元素 状态集&#xff1a;表示智能体所处所有状态的全部可能性的集合。类似的集合&#xff0c;行为集&#xff0c;回报集决策&#xff1a;规定我在某个状态下&#xff0c;我做出某个action马尔可夫链&#xff1a;学术上来说是无记忆性质。说白了就是我只在乎我目前的状态。…...

SpringBoot自写项目记录

设置静态资源映射 Slf4j 用来打印日志 Configuration Slf4j //设置静态资源映射 public class WebMvcConfig extends WebMvcConfigurationSupport {Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {log.info("开始静态资源配置");r…...