SpringBoot/SpringMVC 下载本地文件

页面代码:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>标题</title>
    </head>

     <body>
            <h2>It works!</h2>
            <a href="/downloadLocalXlsxFile">Local xlsx file download</a>
     </body>
</html>
<script type="text/javascript">
<!--
    // 脚本
//-->
</script>

后台代码:

package com.example.demo;

import java.io.FileInputStream;
import java.net.URLDecoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@SpringBootApplication
public class SpringBootWeb1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootWeb1Application.class, args);
    }

    @RequestMapping("/")
    public String index() {
        return "index.html";
    }

    @RequestMapping("/downloadLocalXlsxFile")
    public void downloadLocalXlsxFile(HttpServletResponse res, HttpServletRequest req) throws Exception {
        String localFilename = "Book1.xlsx";
        String localFilepath = getClass().getResource("/templates/" + localFilename).getPath();
        
        res.setContentType("multipart/form-data");
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/html");
        
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            // IE Core
            localFilename = java.net.URLEncoder.encode(localFilename, "UTF-8");
        } else {
            // Non-IE Core
            localFilename = new String((localFilename).getBytes("UTF-8"), "ISO-8859-1");
        }
        res.setHeader("Content-Disposition", "attachment;fileName=" + localFilename);
        
        localFilepath = URLDecoder.decode(localFilepath, "UTF-8");
        FileInputStream instream = new FileInputStream(localFilepath);
        ServletOutputStream outstream = res.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[1024];
        while ((b = instream.read(buffer)) != -1) {
            outstream.write(buffer, 0, b);
        }
        instream.close();

        if (outstream != null) {
            outstream.flush();
            outstream.close();
        }
    }
}
原文地址:https://www.cnblogs.com/heyang78/p/11737422.html