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

 

(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";}

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/118598.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

XSS的分析

目录 1、XSS的原理 2、XSS的攻击类型 2.1 反射型XSS 2.2 存储型XSS 2.3 DOM-based 型 2.4 基于字符集的 XSS 2.5 基于 Flash 的跨站 XSS 2.6 未经验证的跳转 XSS 3、复现 3.1 反射性 3.2 DOM-based型 1、XSS的原理 XSS的原理是恶意攻击者往 Web 页面里插入恶意可执行…

Android中级——消息机制

消息机制 概念ThreadLocalMessageQueueLooperHandlerrunOnUiThread() 概念 MessageQueue&#xff1a;采用单链表的方法存储消息列表Looper&#xff1a;查询MessageQueue是否有新消息&#xff0c;有则处理&#xff0c;无则等待ThreadLocal&#xff1a;用于Handler获取当前线程的…

TypeScript配置-- 1. 新手处理TS文件红色波浪线的几种方式

Typescript 规范化了JS的项目开发&#xff0c;但是对一些项目的一些新手来说&#xff0c;确实是不怎么优好&#xff0c;譬如我&#xff1a;将我之前珍藏的封装JS代码&#xff0c;拿进了配置了tsconfig.json的vue3项目&#xff0c;在vscode下&#xff0c;出现了满屏的红色 &…

UML四大关系

文章目录 引言UML的定义和作用UML四大关系的重要性和应用场景关联关系继承关系聚合关系组合关系 UML四大关系的进一步讨论UML四大关系的实际应用软件开发中的应用其他领域的应用 总结 引言 在软件开发中&#xff0c;统一建模语言&#xff08;Unified Modeling Language&#x…

如何在Spring Boot应用中使用Nacos实现动态更新数据源

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…

STM32G0 定时器PWM DMA输出驱动WS2812配置 LL库

通过DMA方式输出PWM模拟LED数据信号 优点&#xff1a;不消耗CPU资源 缺点&#xff1a;占用内存较大 STM32CUBEMX配置 定时器配置 定时器通道&#xff1a;TIM3 CH2 分频&#xff1a;0 重装值&#xff1a;79&#xff0c;芯片主频64Mhz&#xff0c;因此PWM输出频率&#xff1a…

(超简单)将图片转换为ASCII字符图像

将一张图片转换为ASCII字符图像 原图&#xff1a; 效果图&#xff1a; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileWriter; import java.io.IOException;public class ImageToASCII {/*** 将图片转换为A…

c#继承(new base)的使用

概述 C#中的继承是面向对象编程的重要概念之一&#xff0c;它允许一个类&#xff08;称为子类或派生类&#xff09;从另一个类&#xff08;称为父类或基类&#xff09;继承属性和行为。 继承的主要目的是实现代码重用和层次化的组织。子类可以继承父类的字段、属性、方法和事…

睿趣科技:抖音开小店大概多久可以做起来

随着移动互联网的快速发展&#xff0c;社交媒体平台成为了人们分享生活、交流信息的主要渠道之一。在众多社交平台中&#xff0c;抖音以其独特的短视频形式和强大的用户粘性受到了广泛关注。近年来&#xff0c;越来越多的人通过在抖音上开设小店来实现创业梦想&#xff0c;这种…

Nat. Commun.2023 | AI-Bind+:提高蛋白质配体结合预测的通用性

论文标题&#xff1a;Improving the generalizability of protein-ligand binding predictions with AI-Bind 论文地址&#xff1a;Improving the generalizability of protein-ligand binding predictions with AI-Bind | Nature Communications 代码&#xff1a; Barabasi…

2、Spring6 入门

1、环境要求 JDK&#xff1a;Java17&#xff08;Spring6要求JDK最低版本是Java17&#xff09; Maven&#xff1a;3.6 Spring&#xff1a;6.0.2 2、构建模块 2.1 构建父模块spring6 点击“Create” 2.2 构建子模块spring-first 点击 Create 完成. 3、程序开发 3.1 引入依…

lnmp架构-mysql1

1.MySQL数据库编译 make完之后是这样的 mysql 初始化 所有这种默认不在系统环境中的路径里 就这样加 这样就可以直接调用 不用输入路径调用 2.初始化 重置密码 3.mysql主从复制 配置master 配置slave 当master 端中还没有插入数据时 在server2 上配slave 此时master 还没进…

Qt +VTK+Cmake 编译和环境配置(第一篇 采坑)

VTK下载地址&#xff1a;https://vtk.org/download/ cmake下载地址&#xff1a;https://cmake.org/download/ 版本对应方面&#xff0c;如果你的项目对版本没有要求&#xff0c;就不用在意。我就是自己随机搭建的&#xff0c;VTK选择最新版本吧&#xff0c;如果后面其他的库不…

LeetCode56.合并区间

这道题我想了一会儿&#xff0c;实在想不到比较好的算法&#xff0c;只能硬着头皮写了&#xff0c;然后不断的debug&#xff0c;经过我不懈的努力&#xff0c;最后还是AC&#xff0c;不过效率确实低。 我就是按照最直接的方法来&#xff0c;先把intervals数组按照第一个数star…

Python小知识 - 一个简单的Python爬虫实例

一个简单的Python爬虫实例 这是一个简单的Python爬虫实例&#xff0c;我们将使用urllib库来下载一个网页并解析它。 首先&#xff0c;我们需要安装urllib库&#xff1a; pip install urllib接下来&#xff0c;我们来看看如何使用urllib库来下载一个网页&#xff1a; import url…

【数据结构Java版】 初识泛型和包装类

目录 1.包装类 1.1基本数据类型以及它们所对应的包装类 1.2装箱和拆箱 1.3自动装箱和自动拆箱 2.什么是泛型 3.引出泛型 4.泛型类的使用 4.1语法 4.2示例 4.3类型推导 5.泛型是如何编译的 5.1擦除机制 5.2正确的写法 6.泛型的上届 6.1语法 6.2示例 …

Spring Cloud 微服务2

Eureka 注册中心&#xff0c;服务的自动注册、发现、状态监控 Ribbon 负载均衡&#xff0c;Eureka中已经集成了负载均衡组件 Hystrix 熔断器&#xff0c;用于隔离访问远程服务、第三方库&#xff0c;防止出现级联失败。 Feign 远程调用&#xff0c;将Rest的请求进行隐藏&a…

《开发实战》13 | 用好Java 8的日期时间类,少踩一些“老三样”的坑

13 | 用好Java 8的日期时间类&#xff0c;少踩一些“老三样”的坑 初始化日期时间 如果要初始化一个 2019 年 12 月 31 日 11 点 12 分 13秒这样的时间&#xff0c;Date date new Date(2019, 12, 31, 11, 12, 13);输出的时间是 3029 年 1 月 31 日 11 点 12 分 13 秒&#xf…

springboot web开发整合Freemarker 模板引擎

目录 Freemarker添加依赖配置文件ymlcontrollerhtml Freemarker 简介&#xff1a; FreeMarker 是一款 模板引擎&#xff1a; 即一种基于模板和要改变的数据&#xff0c; 并用来生成输出文本(HTML网页&#xff0c;电子邮件&#xff0c;配置文件&#xff0c;源代码等)的通用工具…

Git学习——细节补充

Git学习——细节补充 1. git diff2. git log3. git reset4. git reflog5. 提交撤销5.1 当你改乱了工作区某个文件的内容&#xff0c;想直接丢弃工作区的修改时5.2 当提交到了stage区后&#xff0c;想要退回 6. git remote7. git pull origin master --no-rebase8. 分支管理9. g…