SpringMVC实战教程 | 第八篇:SpringMVC下载文件

为了将像文件这样的资源发送到浏览器,需要在控制器中完成以下工作:
(1)对请求处理方法使用void返回类型,并在方法中添加HttpServletResponse参数。
(2)将响应的内容类型设为文件的内容类型。Content-Type标题在某个实体的body中定义数据的类型,并包含媒体类型和子类型标识符。
(3)添加一个名为Content-Disposition的HTTP响应标题,并赋值attachment; filename=fileName,这里的fileName是默认文件名,应该出现在File Download(文件下载)对话框中。它通常与文件同名,但是也并非一定如此。

ResourceController

@Controller
public class ResourceController {
    private static final Log logger = LogFactory
            .getLog(ResourceController.class);

    @RequestMapping(value = "/login")
    public String login(@ModelAttribute Login login, HttpSession session,
            Model model) {
        model.addAttribute("login", new Login());
        if ("paul".equals(login.getUserName())
                && "secret".equals(login.getPassword())) {
            session.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, "secret.pdf");
        if (file.exists()) {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition.pdf",
                    "attachment;filename=secret.pdf");
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;

            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 (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {

                if (bis != null) {
                    try {
                        bis.close();
                    } catch (Exception e2) {
                    }
                }

                if(fis!=null){
                    try {
                        fis.close();
                    } catch (Exception e2) {
                    }
                }

            }
        }
        return null;
    }
}

Login

public class Login  implements Serializable {
    private static final long serialVersionUID = -38L;

    private String userName;
    private String password;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

LoginForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login</title>
</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>

Main.jsp

Main.jsp页面中包含了一个链接,用户可以单击它来下载文件。

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<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>

这里写图片描述
这里写图片描述
这里写图片描述

防止交叉引用

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd    
    ">

    <context:component-scan base-package="controller2" />

    <mvc:annotation-driven />

    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/*.html" location="/" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>



</beans>

imageController

@Controller
public class ImageController {
    private static final Log logger = LogFactory.getLog(ImageController.class);

    @RequestMapping(value = "/image_get/{id}", method = RequestMethod.GET)
    public void getImage(@PathVariable String id, HttpServletRequest request,
            HttpServletResponse response, @RequestHeader String 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;

                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 (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {

                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (Exception e2) {
                        }
                    }

                    if(fis!=null){
                        try {
                            fis.close();
                        } catch (Exception e2) {
                        }
                    }

                }
            }
        }
    }
}

images,html

<html>
<head>
<title>Photo</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>

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值