Spring Boot文件上传和下载

文件上传
编写文件上传的表单页面,在templates模板引擎文件夹下创建一个用来上传文件的upload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动态添加上传文件</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <script th:src="@{/login/js/jquery-2.0.3.min.js}"></script>
</head>
<body>
    <div th:if="${uploadStatus}" style="color: red" th:text="${uploadStatus}">
        上传成功
    </div>
    <form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">
        上传文件:&nbsp;&nbsp;
        <input type="button" value="添加文件" onclick="add()">
        <div id="file" style="margin-top: 10px;" th:value="文件上传区域"></div>
        <input id="submit" type="submit" value="上传"
               style="display: none;margin-top: 10px"/>
    </form>
<script>
//动态添加上传按钮
    function add(){
        var innerdiv = "<div>";
        innerdiv += "<input type='file' name='fileUpload' required='required'>"+
            "<input type='button' value='删除' onclick='remove(this)'>";
        innerdiv += "</div>";
        $("#file").append(innerdiv);
        $("#submit").css("display","block");
    }
    //删除当前行<div>
    function remove(obj) {
        $(obj).parent().remove();
        if ($("#file div").length == 0){
            $("#submit").css("display","none");
        }
    }
</script>
</body>
</html>

在全局文件中添加文件上传的相关配置

# 单个上传文件大小限制(默认1MB)
spring.servlet.multipart.max-file-size=10MB
# 总上传文件大小限制(默认10MB)
spring.servlet.multipart.max-request-size=50MB

文件下载
英文名文件下载,需要引入文件下载的工具依赖commons-io
本实例中的“E:/file/”目录存在’bloglogo.txt和Spring Boot应用开发教程.txt文件

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

定制文件下载页面,在templates模板引擎文件夹下创建一个用来上传文件的download.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件下载</title>
</head>
<body>
    <div style="margin-bottom: 10px">文件下载列表:</div>
    <table>
        <tr>
            <td>bloglogo.txt</td>
            <td><a th:href="@{/download(filename='bloglogo.txt')}">下载文件</a> </td>
        </tr>
        <tr>
            <td>Spring Boot应用开发教程.txt</td>
            <td><a th:href="@{/download(filename='Spring Boot应用开发教程.txt')}">
                下载文件</a></td></td>
        </tr>
    </table>
</body>
</html>

进行文件上传,下载处理,实现文件上传、下载功能
新建controller包在该包下创建一个管理文件上传下载的控制类FileController

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
public class FileController {
//向文件上传页面跳转
    @GetMapping("/toUpload")
    public String toUpload(){
        return "upload";
    }
//文件上传管理
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model){
    //默认文件上传成功并返回状态信息
        model.addAttribute("uploadStatus","上传成功!");
        for (MultipartFile file : fileUpload){
        //获取文件名以及后缀名
            String fileName = file.getOriginalFilename();
            //重新生成文件名(根据具体情况生成对应的文件名)
            fileName = UUID.randomUUID()+"_"+fileName;
            //指定上传文件本地存储目录,不存在则需要提前创建
            String dirPath = "E:/file/";
            File filePath = new File(dirPath);
            if (!filePath.exists()){
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(dirPath+fileName));
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("uploadStatus","上传失败:"+e.getMessage());
            }
        }
        //携带上传状态信息回调到文件上传页面
        return "upload";
    }

    @GetMapping("/toDownload")
    public String toDownload(){
        return "download";
    }
//文件下载管理
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws Exception {
    //指定要下载的文件根路径
        String dirPath = "E:/file/";
        //创建文件对象
        File file = new File(dirPath + File.separator + filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        filename = getFilename(request, filename);
        //通知浏览器以下载的形式打开
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回页面文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }

    //根据浏览器的不同进行编码设置,返回编码后的文件名,解决中文名文件的下载
    private String getFilename(HttpServletRequest request,String filename) throws Exception {
        //IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords={"MSIE","Trident","Edge"};
        //获取请求头中的”User-Agent“
        String userAgent = request.getHeader("User-Agent");
        for(String keyWord : IEBrowserKeyWords){
            if (userAgent.contains(keyWord)) {
                //国内的浏览器,统一为UTF-8编码要求,并对转换的+进行更正
                return URLEncoder.encode(filename,"UTF-8").replace("+"," ");
            }
        }
//        火狐等其他浏览器同意编码为”ISO-8859-1“,编码显示
        return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值