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

news2024/10/7 12:21:08

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

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

windows如何更改/禁用系统更新

提示&#xff1a;首先说明这属于将更新时间更改&#xff0c;不过你可以的将更新时间更改为十年一百年 废话不多说开始正文&#xff1a; 1.首先:winR打开运行&#xff0c;输入regedit&#xff0c;进入注册表编辑器 2.进入编辑器后依次点击&#xff1a;HKEY_LOCAL_MACHINE\SOFT…

Clion 使用ffmpeg 学习1 开发环境配置

Clion 使用ffmpeg 学习1 开发环境配置 一、准备工作1. 准备环境2. 下载FFmpeg 二、操作步骤1. Clion 新建一个C项目2. 修改 CMakeLists.txt3. 修改配置4. 运行测试5. 打印rtsp 流信息的 demo 一、准备工作 在视频处理和多媒体应用程序开发中&#xff0c;FFmpeg 是一个强大的开…

学生辅导反馈

1 密西根大学 这个留学生了一个A。 他的C课程比较简单&#xff0c;属于入门级&#xff0c;大部分自己都可以搞定&#xff0c;只不过如果有人带一下就会彻底理解&#xff0c;自信心也就上来了。 基本上都是一对一&#xff0c;他写代码&#xff0c;我看着。 不过他后面想选他们…

系统调用与函数地址动态寻找(详解版)

双机调试 F9&#xff0c;进入程序领空&#xff0c;搜索所有用户模块的跨模块调用&#xff0c;F2下断点 x64Dbg&#xff1a;F7单步步入&#xff0c;F8单步步过 进入内核的方式&#xff1a; int 2E&#xff08;比较早期&#xff09;sysenter&#xff08;x86&#xff09;sysca…

Python入门教程 | Python3 列表(List)

Python3 列表 序列是 Python 中最基本的数据结构。 序列中的每个值都有对应的位置值&#xff0c;称之为索引&#xff0c;第一个索引是 0&#xff0c;第二个索引是 1&#xff0c;依此类推。 Python 有 6 个序列的内置类型&#xff0c;但最常见的是列表和元组。 列表都可以进…

CPU彪高排序顺序

简单总结 这类问题分为两大类 代码问题JVM自身问题 我们首先要做的就是先保证代码无bug&#xff0c;排查顺序就是 进程 -> 线程 -> jstack 分析&#xff0c;最后在做JVM的分析。 具体操作 对于Java后台程序CPU使用率高的排查&#xff0c;可以按以下步骤操作&#xf…

解决:burpsuite——Connection refused: no further information

出现该问题的原因是开启了SOCKS proxy&#xff1b;关闭该选项即可正常抓包。 具体操作&#xff1a;

Windows安装配置Rust(附CLion配置与运行)

Windows安装配置Rust&#xff08;附CLion配置与运行&#xff09; 前言一、下载二、安装三、配置标准库&#xff01;&#xff01;&#xff01;四、使用 CLion 运行 rust1、新建rust项目2、配置运行环境3、运行 前言 本文以 windows 安装为例&#xff0c;配置编译器为 minGW&…

flutter plugins插件【一】【FlutterJsonBeanFactory】

1、FlutterJsonBeanFactory 在Setting->Tools->FlutterJsonBeanFactory里边自定义实体类的后缀&#xff0c;默认是entity 复制json到粘贴板&#xff0c;右键自己要存放实体的目录&#xff0c;可以看到JsonToDartBeanAction Class Name是实体名字&#xff0c;会默认加上…

Python入门教程32:计算程序运行的时间

★★★★★博文原创不易&#xff0c;我的博文不需要打赏&#xff0c;也不需要知识付费&#xff0c;可以白嫖学习编程小技巧&#xff0c;喜欢的老铁可以多多帮忙点赞&#xff0c;小红牛在此表示感谢。★★★★★ #我的Python教程 #官方微信公众号&#xff1a;wdPythonPython中可…

stable diffusion实践操作-CLIP

系列文章目录 stable diffusion实践操作 文章目录 系列文章目录前言一、CLIP是什么&#xff1f;1.1 定义&#xff1a;1.2 作用 二、使用步骤2.1 设置使用2.1 跳过层对比图&#xff1a; 三、总结 前言 学习本章之前&#xff0c;先看SD生图原理 stable diffusion实践操作-SD原理…

看看985高校的《数据结构》教材能差到什么程度

网上下了一本教材&#xff0c;看看其内容&#xff0c;不禁开始吃鲸起来。我们的国家的栋梁之材就天天学习这样的教材。 国内外教材但凡多参考也不至于差到如此地步。清华严蔚敏的那本参考一下也不至于写出这么差的教材。 而且用C实现。C被误导&#xff0c;误教&#xff0c;不…

【回溯法-附模板和例题分析】

回溯法 适用于&#xff1a; 组合问题&#xff1a;N个数里面按一定规则找出k个数的集合切割问题&#xff1a;一个字符串按一定规则有几种切割方式子集问题&#xff1a;一个N个数的集合里有多少符合条件的子集排列问题&#xff1a;N个数按一定规则全排列&#xff0c;有几种排列…

LeetCode 面试题 02.08. 环路检测

文章目录 一、题目二、C# 题解 一、题目 给定一个链表&#xff0c;如果它是有环链表&#xff0c;实现一个算法返回环路的开头节点。若环不存在&#xff0c;请返回 null。 如果链表中有某个节点&#xff0c;可以通过连续跟踪 next 指针再次到达&#xff0c;则链表中存在环。 为了…

接口测试系列 —— POSTMAN的简单使用

postman的基本使用 概述 我相信对于postman的介绍&#xff0c;网上一搜肯定很多很多。下面我就不打算跟大家普及postman了。只看应该怎么用postman进行接口测试。好了&#xff0c;下面咱们直接进入正文吧。 环境 postman之前是作为chrome插件形式存在的。后面变成了独立的应…

【zip密码】zip压缩包删除密码方法

Zip压缩包设置设置了密码&#xff0c;想要删除密码&#xff0c;除了将压缩包解压出来之后再将文件压缩为不带密码的压缩文件以外&#xff0c;还有一种删除密码的方法。设置方法如下&#xff1a; 右键点击zip文件&#xff0c;找到打开方式&#xff0c;以Windows资源管理器方式打…

【STM32】学习笔记(OLED)

调试方式 OLED简介 硬件电路 驱动函数 OLED.H #ifndef __OLED_H #define __OLED_Hvoid OLED_Init(void); void OLED_Clear(void); void OLED_ShowChar(uint8_t Line, uint8_t Column, char Char); void OLED_ShowString(uint8_t Line, uint8_t Column, char *String); void OL…

aarch64-linux交叉编译libcurl带zlib和openssl

交叉编译libcurl需要依赖zlib和openssl 需要先用aarch64工具链编译zlib和openssl aarch64-linux环境搭建 下载工具链 gcc用于执行交叉编译 gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnusysroot是交叉版本的库文件集合 sysroot-glibc-linaro-2.25-2019.12-aarch64-lin…

仿`gRPC`功能实现像调用本地方法一样调用其他服务器方法

文章目录 仿gRPC功能实现像调用本地方法一样调用其他服务器方法 简介单体架构微服务架构RPCgPRC gRPC交互逻辑服务端逻辑客户端逻辑示例图 原生实现仿gRPC框架编写客户端方法编写服务端方法综合演示 仿 gRPC功能实现像调用本地方法一样调用其他服务器方法 简介 在介绍gRPC简介…

双网卡/内外网同时使用2023.09.01

1.双网卡 电脑需要两个网卡&#xff1a;两个网口或者是一个有线网卡加一个无线网卡。 查看网关&#xff1a;如下网口接入网线后&#xff0c;电脑连接WIFI&#xff0c;电脑会显示存在两个网卡正在使用&#xff08;电脑存在两个IP地址&#xff09; 查看本地的路由设置 route p…