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. tcpreplay工具安装使用

    一.Tcpreplay功能简介 首先推荐一个网站:http://tcpreplay.synfin.net/ ,上面有Tcpreplay的安装包和很多文档,包括手册.man页和FAQ等. Tcprepl ...

  2. imx6背光驱动调试

    1.内核配置pwm背光驱动make menuconfig:Device Driver ---> Graphics support ---> [*] Backlight & LCD ...

  3. android属性动画之ValueAnimator

    楼主前段时间做一个android项目,其中一个需求是需要制作一个动画,但是之前楼主没接触过android动画,所以在网上搜了下,并且也有人推荐可以试下用属性动画,所以我就百度了下属性动画怎么用,并顺便 ...

  4. git 显示多个url地址推送

    前提 一般来说,我们为git增加远程库,一般都是git remote add origin <url> ( 你可以使用真实的地址来代替 \<url\> ) 但是你可能想要把你的 ...

  5. mac - MAC电脑安装Mysql服务器和Navicat for mysql客户端

        1.下载链接 Navicat for mysql客户端 链接: https://pan.baidu.com/s/1dGbzgbR 密码: i43g Mysql服务器 链接: https://p ...

  6. 高性能图片服务器–ZIMG(转)

    2011年李彦宏在百度联盟峰会上就提到过互联网的读图时代已经到来1,图片服务早已成为一个互联网应用中占比很大的部分,对图片的处理能力也相应地变成企业和开发者的一项基本技能.需要处理海量图片的典型应用有 ...

  7. python time与datetime.date/datetime模块

    https://docs.python.org/3/library/datetime.html 1.用于日期比较大小的方法 方法名 方法说明 用法 __eq__(…) 等于(x==y) x.__eq_ ...

  8. 【BZOJ3029】守卫者的挑战 概率+背包

    [BZOJ3029]守卫者的挑战 Description 打开了黑魔法师Vani的大门,队员们在迷宫般的路上漫无目的地搜寻着关押applepi的监狱的所在地.突然,眼前一道亮光闪过.“我,Nizem, ...

  9. Java 科学计数法

    目录 Java 科学计数法 1 科学计数法的概念 1.1 有效数字 1.2 E记号 2 Java中的科学计数法 2.1 NumberFormat 2.2 DecimalFormat 2.3 BigDe ...

  10. 类 String、StringBuffer、StringBuilder

    类 String String 类代表字符串.Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现.字符串是常量:它们的值在创建之后不能更改.字符串缓冲区支持 ...