Spring MVC-10循序渐进之文件下载

简介: Spring MVC-10循序渐进之文件下载

概述


像静态资源,我们在浏览器中打开正确的URL即可下载,只要该资源不是放在WEB-INF目录下,Servlet/JSP容器就会将该资源发送到浏览器。 然而有的时候静态资源是保存在应用程序目录外或者存在数据库中,或者有的时候需要控制它的访问权限,防止其他网站交叉引用它。 如果出现上述任意一种情况,都必须通过编程来发送资源。


文件下载概览


为了将像文件这样的资源发送到浏览器,需要在控制器中完成以下工作


1. 队请求处理方法使用void返回类型,并在方法中添加HttpServletRespinse参数


2. 将响应的内容设置为文件的内容类型。 Content-Type标题在某个实体的body中定义数据的类型,并包含没提类型和子类型标示符。如果不清楚内容类型,并且希望浏览器始终显示Save As(另存为)对话框,则将它设置为APPLICATION/OCTETPSTREAM ,不区分大小写


3. 添加一个名为Content-Dispositionde HTTP响应标题,并赋值attachment;filename=fileName.这里的fileName是默认文件名,应该出现在File Download对话框中,它通常与文件名同名,但是也并非一定如此


下面的代码是将一个文件发送到浏览器

FileInputStream fis = new FileInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bytes = new byte[bis.available()];
response.setContentType(contentType);
OutputStream os = response.getOutputStream();
bis.read(bytes);
os.write(bytes);

为了通过编程将一个文件发送到浏览器,首先要读取该文件作为FileInputStream,并将内容加载到一个字节数组。 随后,获取HttpServletResponse的OutputStream,并调用其write方法传入字节数组。


隐藏资源



20180306204410369.png


该示例演示如何向浏览器发送文件,由ResourceController类处理用户登录请求,并将WEB-INF/data目录下的artisan.pdf发送给浏览器。因为文件放到了WEB-INF目录下,所以不能够直接访问,只有得到授权的用户才能看到,如果未登录,返回登录页面。


ResourceController, 这里模拟下用户登录,只有当用户的HttpSession中包含一个loggedIn属性时,表明登录成功。

package com.artisan.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.artisan.domain.Login;
@Controller
public class ResourceController {
    @RequestMapping(value = "/login")
    public String login(@ModelAttribute Login login, HttpSession httpSession, Model model) {
        model.addAttribute("login", new Login());
        if ("artisan".equals(login.getUserName()) && "artisan123".equals(login.getPassword())) {
            httpSession.setAttribute("loggedIn", Boolean.TRUE);
            return "Main";
        } else {
            return "LoginForm";
        }
    }
    @RequestMapping(value = "/resource_download")
    public String downLoadResource(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        if (session == null && session.getAttribute("loggedIn") == null) {
            return "LoginForm";
        }
        String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/data");
        File file = new File(dataDirectory, "artisan.pdf");
        if (file.exists()) {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=artisan.pdf");
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            // JDK7 以前的写法
            // try {
            // fis = new FileInputStream(file);
            // bis = new BufferedInputStream(fis);
            // OutputStream os = response.getOutputStream();
            // int i = bis.read(buffer);
            // while (i != -1) {
            // os.write(buffer, 0, i);
            // i = bis.read(buffer);
            // }
            // } catch (IOException ex) {
            // // do something,
            // // probably forward to an Error page
            // } finally {
            // if (bis != null) {
            // try {
            // bis.close();
            // } catch (IOException e) {
            // }
            // }
            // if (fis != null) {
            // try {
            // fis.close();
            // } catch (IOException e) {
            // }
            // }
            // }
            //
            // Java 7, use try-with-resources,自动释放资源
            try (OutputStream os = response.getOutputStream();) {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // do something, 
                // probably forward to an Error page
            }
        }
        return null;
    }
}

login方法,将用户带到登录表单页面

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
<form:form commandName="login" action="login" method="post">
    <fieldset>
        <legend>Login</legend>
        <p>
            <label for="userName">User Name: </label>
            <form:input id="userName" path="userName" cssErrorClass="error"/>
        </p>
        <p>
            <label for="password">Password: </label>
            <form:password id="password" path="password" cssErrorClass="error"/>
        </p>
        <p id="buttons">
            <input id="reset" type="reset" tabindex="4">
            <input id="submit" type="submit" tabindex="5" 
                value="Login">
        </p>
    </fieldset>
</form:form>
</div>
</body>
</html>


用户名和密码在login方法中使用硬编码的方式模拟用户登录,成功后跳转到Main.jsp页面,该页面包含一个超链接,点击下载文件。

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Download Page</title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
    <h4>Please click the link below.</h4>
    <p>
        <a href="resource_download">Download</a>
    </p>
</div>
</body>
</html>


测试

20180306205044406.png

20180306205342599.png

点击链接


20180306205156940.png


查看下载的文件

20180306205222954.png



防止交叉引用



20180306204410369.png


为了防止他人引用我们网站的资源,可以通过编程的方式,只有当请求的报头referer标题中包含你的域名时才发出资源,当然了这种方式也不能完全阻止。

该示例中,ImageController类中,只有referer标题不为空时,才将图片发送给浏览器

package com.artisan.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ImageController {
    @RequestMapping("/imageList")
    public String getImageList(){
        return "Image"; 
    }
    @RequestMapping(value = "/image_get/{id}", method = RequestMethod.GET)
    public void getImage(@PathVariable String id, HttpServletRequest request, HttpServletResponse response,
            @RequestHeader String referer) {
        // 判断请求头中的Referer
        if (referer != null) {
            String imageDirectory = request.getServletContext().getRealPath("/WEB-INF/image");
            File file = new File(imageDirectory, id + ".jpg");
            if (file.exists()) {
                response.setContentType("image/jpg");
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                // if you're using Java 7, use try-with-resources
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException ex) {
                    // do something here
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        }
    }
}

前台页面

<!DOCTYPE HTML>
<html>
<head>
<title>Images</title>
</head>
<body>
<img src="image_get/1"/>
<img src="image_get/2"/>
<img src="image_get/3"/>
<img src="image_get/4"/>
<img src="image_get/5"/>
<img src="image_get/6"/>
<img src="image_get/7"/>
<img src="image_get/8"/>
<img src="image_get/9"/>
<img src="image_get/10"/>
</body>
</html>



测试:

20180306210153301.png


源码


代码已提交到github

https://github.com/yangshangwei/SpringMvcTutorialArtisan

相关文章
|
Java 测试技术 Spring
Spring Boot入门(11)实现文件下载功能
  在这篇博客中,我们将展示如何在Spring Boot中实现文件的下载功能。   还是遵循笔者写博客的一贯风格,简单又不失详细,实用又能让你学会。
2372 0
|
Java API Spring
spring boot中Excel文件下载踩坑大全
spring boot中Excel文件下载踩坑大全
2374 2
spring boot中Excel文件下载踩坑大全
|
存储 安全 Java
Spring Boot中的文件下载实现
Spring Boot中的文件下载实现
|
Java Spring
spring boot 实现文件下载
主要介绍了spring boot 实现文件下载
|
3月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
757 0
|
7月前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
331 0
|
7月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
323 0
|
7月前
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
103 0
|
7月前
|
SQL Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— application.yml 中对日志的配置
在 Spring Boot 项目中,`application.yml` 文件用于配置日志。通过 `logging.config` 指定日志配置文件(如 `logback.xml`),实现日志详细设置。`logging.level` 可定义包的日志输出级别,例如将 `com.itcodai.course03.dao` 包设为 `trace` 级别,便于开发时查看 SQL 操作。日志级别从高到低为 ERROR、WARN、INFO、DEBUG,生产环境建议调整为较高级别以减少日志量。本课程采用 yml 格式,因其层次清晰,但需注意格式要求。
640 0
|
3月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
406 0
第07课:Spring Boot集成Thymeleaf模板引擎