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. win7安装RabbitMQ

    1.下载并安装erlang http://www.erlang.org/downloads 2.下载并安装RabbitMQ http://www.rabbitmq.com/install-window ...

  2. OSX: bash的更新

    本文尽量详述眼下来说的bash补丁的进展,从以下4个方面解释: 最全最新的更新安装包,:Oct 5为止的 測试已知的bash漏洞的脚本:更新后能够用来检測已知bash漏洞的情况 脚本编译更新版本号:也 ...

  3. Death to Binary? 分析模拟

    /** 题目:Death to Binary? 链接:https://vjudge.net/contest/154246#problem/T 题意:略. 思路: 注意事项: 给的字符串存在前导0: 存 ...

  4. Kafka具体解释五、Kafka Consumer的底层API- SimpleConsumer

    1.Kafka提供了两套API给Consumer The high-level Consumer API The SimpleConsumer API 第一种高度抽象的Consumer API,它使用 ...

  5. SHA信息摘要

    SHA算法是在MD4的基础上演进而来的,通过SHA算法能够获得一个固定长度的摘要信息.   SHA算法系列有SHA-1(也成为SHA),SHA-224,SHA-256,SHA-384和SHA-512这 ...

  6. 通过Get方式传递数据

    1:因为get传参数有个特点就是不能超过256字节.如果数据大的话会溢出. 解决办法: $data=json_encode($data_array); 然后在拼接超链接: <a href=&qu ...

  7. A Survey of Shape Feature Extraction Techniques中文翻译

    Yang, Mingqiang, Kidiyo Kpalma, and Joseph Ronsin. "A survey of shape feature extraction techni ...

  8. Spring MVC文本域

    以下示例显示如何在使用Spring Web MVC框架的表单中使用文本域(TextArea).首先使用Eclipse IDE来创建一个WEB工程,并按照以下步骤使用Spring Web Framewo ...

  9. echarts(3.0)的基本使用(标签式导入)

    function loadRainFallCharts(msg) { var obj = {}; obj.x = []; obj.y = []; obj.line = []; var accumula ...

  10. windows文件打包命令

    copy /Y partition.bin /b + qcsblhd_cfgdata.bin /b + qcsbl.bin /b + oemsbl.bin /b + fat.amss.bin /b + ...