SpringMVC 下载文件<7>

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

  1. 对请求处理方法使用void返回类型,并在方法中添加HttpServletResponse参数。
  2. 将响应的内容类型设为文件的内容类型。Content-Type标题在某个实体的body中定义数据的类型,并包含媒体类型和子类型标识符。如果不清楚类型,并希望浏览器始终显示Save As对话框,则将它设为APPLICATION/OCTET-STREAM。不区分大小写。
  3. 添加一个名为Content-Disposition的HTTP响应标题,并赋值attachment;filaname=fileName,这里的fileName是默认文件名,应该出现在FileDownload(文件下载)对话框中。

为防止交叉引用,使用referer,当包含你的域名时才发出资源。不能严格防范,但获取资源不那么容易了。

  1. controller
package com.company.combine.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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

import com.company.combine.model.User;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.mysql.jdbc.log.LogFactory;

@Controller
public class ResourceController {

    private static final Log logger = org.apache.commons.logging.LogFactory.getLog(ResourceController.class);
    @RequestMapping(value = "/login1")
    public String login(@ModelAttribute User user, HttpSession session, Model model){
        model.addAttribute("login1", new User());
        if("username".equals(user.getUsername())&&"password".equals(user.getPassword())){
            session.setAttribute("loggedIn", Boolean.TRUE);
            return "Main";
        }else{
            return "LoginForm";
        }
    }
    
    @RequestMapping(value = "/resource_download")
    public String saveProduct(HttpServletRequest request,
                              HttpSession session, HttpServletResponse response, @RequestHeader String referer){
        
        if(session == null || session.getAttribute("loggedIn")==null){
            return "LoginForm";
        }
        if (referer == null||!referer.contains("mydomain")) {//检查是否包含自己的域名
            return null;
        }
        String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/data");
        File file = new File(dataDirectory,"GreenDao3.pdf");
        System.out.println("file.getAbsolutePath():"+file.getAbsolutePath());
        if(file.exists()){
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment;filename=GreenDao3.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,1);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                if(bis != null){
                    try {
                        bis.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
                if(fis !=null){
                    try {
                        fis.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
        return null;
    }
}
  1. LoginForm.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="GB2312"%>

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>




登录


    
Login

  1. main.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="GB2312"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>




登录


    

Please click the link below.

Download

  1. 注意在/WEB-INF/data下放置下载文件

你可能感兴趣的:(SpringMVC 下载文件<7>)