(笔记)Spring MVC学习指南_下载文件

像图片或者HTML文件这样的静态资源,在浏览器中打开正确的URL即可下载。只要该资源是放在应用程序的目录下,或者放在应用程序目录的子目录下,而不是放在WEB-INF下,Servlet/JSP容器就会将该资源发送到浏览器。然而,有时静态资源是保存在应用程序目录外,或者是保存在某一个数据库中,或者有时需要控制它的访问权限,防止其他网站交叉引用它。如果出现以上任意一种情况,都必须通过编程来发送资源。
简言之,通过编程进行的文件下载,使你可以有选择地将文件发送到浏览器。
1.文件下载概览
为了将像文件这样的资源发送到浏览器,需要在控制器中完成以下工作:
(1)对请求处理方法使用void返回类型,并在方法中添加HttpServletResponse参数。
(2)将响应的内容类型设为文件的内容类型。Content-Type标题在某个实体的body中定义数据的类型,并包含媒体类型和子类型标识符。
(3)添加一个名为Content-Disposition的HTTP响应标题,并赋值attachment; filename=fileName,这里的fileName是默认文件名,应该出现在File Download(文件下载)对话框中。它通常与文件同名,但是也并非一定如此。
2.范例1:隐藏资源

    @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", "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 (IOException e)
            {

            }
            finally
            {
                if (bis != null)
                {
                    try
                    {
                        bis.close();
                    }
                    catch (IOException e)
                    {}
                }
                if (fis != null)
                {
                    try
                    {
                        fis.close();
                    }
                    catch (IOException e)
                    {}
                }
            }
        }
        return null;
    }

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

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<title>Download Pagetitle>
head>
<body>
    <div id="global">
        <h4>Please click the link below.h4>
        <p>
            <a href="resource_download">Downloada>
        p>
    div>
body>
html>

范例2:防止交叉引用
springmvc-config.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="app12a.controller" />
    <mvc:resources location="/" mapping="/*.html" />
    <mvc:resources location="/image/" mapping="/image/**" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    bean>
beans>

Controller

package app12a.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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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
{

    private static final Log logger = LogFactory.getLog(ImageController.class);

    @RequestMapping(value = "/image_get/{name}", method = RequestMethod.GET)
    public void getImage(@PathVariable String name, HttpServletRequest request,
                         HttpServletResponse response, @RequestHeader String referer)
    {
        if (referer != null)
        {
            String imageDirectory = request.getServletContext().getRealPath("/WEB-INF/image");
            File file = new File(imageDirectory, name + ".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 (IOException e)
                {}
                finally
                {
                    if (bis != null)
                    {
                        try
                        {
                            bis.close();
                        }
                        catch (IOException e)
                        {}
                    }
                    if (fis != null)
                    {
                        try
                        {
                            fis.close();
                        }
                        catch (IOException e)
                        {}
                    }
                }
            }
        }
    }
}

你可能感兴趣的:(SpringMVC)