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

(1)文件上传

 上传文件Spring中需要配置:

 代码:

@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)用户登录

 

(4)修改头像

 获取用户信息:

@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);//重新存入Session
        return "redirect:/person";
    }

现根据前端传来的头像地址,根据头像存储地址获取头像的编号:查询头像编号

更新用户信息,因为用户信息存储的是头像编号 

在重新查询用户信息,存入Session

 

(5)java代码中使用Properties文件中的值

package com.lianshuwang.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertyConfigurer extends PropertyPlaceholderConfigurer {

    //private static Properties props;  // 存取properties配置文件key-value结果

    private static Map<String, String> propertyMap;

    //static method for accessing context properties
    public static Object getProperty(String key) {
        return propertyMap.get(key);
    }

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        propertyMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            propertyMap.put(keyStr, value);
        }
    }

}

在Spring配置文件中配置这个类:

Java代码中使用配置文件中的值:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值