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. 基于windows的resin配置

    Resin 与 Eclipse for JavaEE 的整合方法: 1.新建一个项目,将web application配置到resin.conf中 附上resin_struts2-111.conf文件 ...

  2. 查看文件内容- 删除某个运行程序的所有进程-nohup后台执行程序

    1 查看文件内容: tail -f test.txt 2 查看端口 netstat nlp 3 删除某个运行程序的所有进程 ps -ef|grep translateService.py|grep - ...

  3. ubuntu下telnet安装

    系统默认安装了telnet(client),所以只能用telnet登录别人开启telnet服务的主机,其他人是不能telnet登录本机的. 现在想要的是让别人可以使用telnet登录本机,需要安装两个 ...

  4. JS判断不同的浏览器,不同的浏览器版本

    JS判断不同的浏览器,不同的浏览器版本

  5. Linux 文件管理(C语言库函数三)

    找到当前目录 char *getcwd(char * buf,size_t size) getcwd函数把当前工作目录的绝对路径名复制到buf中,size指示buf的大小 如果buf不够大,不能装下整 ...

  6. wtform 表单示例

    用户注册 from flask import Flask, render_template, request, redirect from wtforms import Form from wtfor ...

  7. Linux学习目录

    一.CentOS for Linux 大神博客:骏马金龙  Linux也可以参考,这篇博客进行学习 http://www.cnblogs.com/f-ck-need-u/p/7048359.html ...

  8. iOS开发常见问题(不断更新)

    1.如何从程序退出到桌面 在单击事件中 exit(0);即可. 2.如何强制横屏 在你需要横屏的控制器里加入如下代码 - (BOOL)shouldAutorotate{ return NO; } - ...

  9. Android 百度语音合成集成

    一.环境配置: 下载资料:http://ai.baidu.com/sdk 官方视频讲解:http://ai.baidu.com/support/video 接入指南:http://ai.baidu.c ...

  10. Codeforces Round #324 (Div. 2) (快速判断素数模板)

    蛋疼的比赛,当天忘了做了,做的模拟,太久没怎么做题了,然后C题这么简单的思路却一直卡到死,期间看了下D然后随便猜了下,暴力了下就过了. A.找一个能被t整除的n位数,那么除了<=10以外,其他都 ...