SpringMVC—文件下载

说明

两个案例

  1.为登录用户提供下载服务。

  2.阻止仅通过输入网址即可获取下载。

文件下载概览

  为了将文件发送给浏览器,我们需要在控制器中完成以下操作:

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

案例1:为登录用户提供下载服务

Domain类

package domain;
public class Login {
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;
}
}

Controller控制器

package controller;

import domain.Login;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*; @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("ms".equals(login.getUsername())&&"123".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,"Blog.zip");
if(file.exists())
{
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition","attachment;filename=Blog.zip");
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 (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
return null;
}
}

编写视图

Main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>DownPage</title>
</head>
<body>
<h4>点击链接下载文件</h4>
<p>
<a href="resource_download" >Down</a>
</p>
</body>
</html>

LoginForm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form:form commandName="login" action="login" method="post">
账号: <br>
<form:input path="username" cssErrorClass="error" id="username"/>
<br> 密码: <br>
<form:input path="password" cssErrorClass="error" id="password"/>
<br> <input type="submit" value="提交">
</form:form>
</body>
</html>

案例2:阻止仅通过输入网址即可获取下载

    @RequestMapping(value = "/resource_download")
public String downloadResource(HttpSession session, HttpServletRequest request, HttpServletResponse response,@RequestHeader String refuer
){
if(refer==null) //通过判断refer来浏览器输入网址就能下载图片的情况
{
  return "LoginForm";
}
String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/data");
File file = new File(dataDirectory,"Blog.zip");
if(file.exists())
{
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition","attachment;filename=Blog.zip");
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 (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
return null;
}
}

  

SpringMVC:学习笔记(9)——文件下载的更多相关文章

  1. 史上最全的SpringMVC学习笔记

    SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...

  2. springmvc学习笔记--REST API的异常处理

    前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...

  3. springmvc学习笔记---面向移动端支持REST API

    前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...

  4. SpringMVC:学习笔记(8)——文件上传

    SpringMVC--文件上传 说明: 文件上传的途径 文件上传主要有两种方式: 1.使用Apache Commons FileUpload元件. 2.利用Servlet3.0及其更高版本的内置支持. ...

  5. springmvc学习笔记(简介及使用)

    springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...

  6. springmvc学习笔记(常用注解)

    springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...

  7. SpringMVC学习笔记之二(SpringMVC高级参数绑定)

    一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...

  8. springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定

    springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定 标签: springmvc springmvc学习笔记13-springmvc注解开发之集合类型參数绑定 数组绑定 需 ...

  9. springmvc学习笔记(19)-RESTful支持

    springmvc学习笔记(19)-RESTful支持 标签: springmvc springmvc学习笔记19-RESTful支持 概念 REST的样例 controller REST方法的前端控 ...

随机推荐

  1. PHP预定义常量DIRECTORY_SEPARATOR

    PHP预定义常量DIRECTORY_SEPARATOR BY 天涯 · // DIRECTORY_SEPARATOR是一个显示系统分隔符的命令,DIRECTORY_SEPARATOR是PHP的内部常量 ...

  2. jsdoc — js注释

    官方文档 http://usejsdoc.org/ - sublime插件 https://github.com/spadgos/sublime-jsdocs - 生成文档 生成html: (1)安装 ...

  3. 应用市场出新规,国内千款应用TargetSdkVersion调查分析

    ​​​近期,谷歌针对Google Play上架应用发布强制性适配Android 8.0公告,要求自2018 年 8 月 1 日起,所有向 Google Play 首次提交的新应用都必须基于 Andro ...

  4. Python 安装 MaxMind GeoLite City

    1.先安装 geoip c library  geoip c library >= 1.4.6 installed on your machine. >= 1.4.6 installed ...

  5. GCD - Extreme (II) for(i=1;i<N;i++) for(j=i+1;j<=N;j++) { G+=gcd(i,j); } 推导分析+欧拉函数

    /** 题目:GCD - Extreme (II) 链接:https://vjudge.net/contest/154246#problem/O 题意: for(i=1;i<N;i++) for ...

  6. CDH配置JAVA_HOME

    jdk成功安装 java -version 正确显示版本 echo $JAVA_HOME  正确输出路径 但CDH链接数据库还是报错: Error: JAVA_HOME is not set and ...

  7. 第一百八十八节,jQuery,选项卡 UI

    jQueryUI,选项卡 UI 学习要点: 1.使用 tabs 2.修改 tabs 样式 3.tabs()方法的属性 4.tabs()方法的事件 5.tabs 中使用 on 选项卡(tab),是一种能 ...

  8. python urllib 和 urllib2

    urllib 和 urllib2 都是接受URL请求的相关模块,但是提供了不同的功能.两个最显著的不同如下: urllib 仅可以接受URL,不能创建 设置了headers 的Request 类实例: ...

  9. Unity3D学习笔记——NGUI之UIGrid

    UIGrid:这个组件可以轻松的让你排列你的组件,并且在运行或是编辑的时候都可以. 效果图如下: 一:使用步骤 1.选择一个panel然后右键Create——Grid 2.为Grid创建几个子Spri ...

  10. 转载:DenseNet算法详解

    原文连接:http://blog.csdn.net/u014380165/article/details/75142664 参考连接:http://blog.csdn.net/u012938704/a ...