Spring4 MVC文件下载实例

这篇文章将向您展示如何使用Spring MVC4执行文件下载,我们将看到应用程序从文件系统内部以及外部文件下载文件。

 

本教程的主要亮点:

下载文件是相当简单的,涉及以下步骤。

  • 创建一个InputStream到文件用于下载。
  • 查找MIME类型下载文件的内容。
    –可以是application/pdf, text/html,application/xml,image/png等等。
  • 将内容类型与上述发现的MIME类型响应(HttpServletResponse)。
    response.setContentType(mimeType);
  • 针对以上找到MIME类型设置内容长度。
    response.setContentLength(file.getLength());//length in bytes
  • 为响应设置内容处理标头。
    response.setHeader(“Content-Disposition”, “attachment; filename=” + fileName); //随着“附件”文件将下载。可能会显示一个“另存为”基于浏览器的设置对话框。

    response.setHeader(“Content-Disposition”, “inline; filename=” + fileName);//通过“内联”浏览器将尝试显示内容到浏览器中(图片,PDF,文本,...)。对于其他内容类型,文件将直接下载。

  • 从InputStream中复制字节响应到 OutputStream。
  • 一旦复制完成后,关闭输入输出流。

完整实施例在下面讨论。


使用到以下技术:

  • Spring 4.2.0.RELEASE
  • Bootstrap v3.3.2
  • Maven 3
  • JDK 1.7
  • Tomcat 8.0.21
  • Eclipse JUNO Service Release 2

现在让我们开始

项目结构

在pom.xml中声明依赖关系

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.yiibai.springmvc</groupId><artifactId>Spring4MVCFileDownloadExample</artifactId><packaging>war</packaging><version>1.0.0</version><name>Spring4MVCFileDownloadExample Maven Webapp</name><properties><springframework.version>4.2.0.RELEASE</springframework.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${springframework.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency></dependencies><build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.4</version><configuration><warSourceDirectory>src/main/webapp</warSourceDirectory><warName>Spring4MVCFileDownloadExample</warName><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins></pluginManagement><finalName>Spring4MVCFileDownloadExample</finalName></build>
</project>

创建控制器

package com.yiibai.springmvc.controller;import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.nio.charset.Charset;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;@Controller
public class FileDownloadController {private static final String INTERNAL_FILE="irregular-verbs-list.pdf";private static final String EXTERNAL_FILE_PATH="C:/mytemp/SpringMVCHibernateManyToManyCRUDExample.zip";@RequestMapping(value={"/","/welcome"}, method = RequestMethod.GET)public String getHomePage(ModelMap model) {return "welcome";}/** Download a file from *   - inside project, located in resources folder.*   - outside project, located in File system somewhere. */@RequestMapping(value="/download/{type}", method = RequestMethod.GET)public void downloadFile(HttpServletResponse response, @PathVariable("type") String type) throws IOException {File file = null;if(type.equalsIgnoreCase("internal")){ClassLoader classloader = Thread.currentThread().getContextClassLoader();file = new File(classloader.getResource(INTERNAL_FILE).getFile());}else{file = new File(EXTERNAL_FILE_PATH);}if(!file.exists()){String errorMessage = "Sorry. The file you are looking for does not exist";System.out.println(errorMessage);OutputStream outputStream = response.getOutputStream();outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));outputStream.close();return;}String mimeType= URLConnection.guessContentTypeFromName(file.getName());if(mimeType==null){System.out.println("mimetype is not detectable, will take default");mimeType = "application/octet-stream";}System.out.println("mimetype : "+mimeType);response.setContentType(mimeType);/* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\""));/* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*///response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));response.setContentLength((int)file.length());InputStream inputStream = new BufferedInputStream(new FileInputStream(file));//Copy bytes from source to destination(outputstream in this example), closes both streams.FileCopyUtils.copy(inputStream, response.getOutputStream());}}

该控制器包括两个文件。一个文件是内部应用(内部资源),和其他文件位于外部的应用程序的文件系统。您的项目一定要改变外部文件的路径。仅用于演示的目的,我们已在路径一个额外的路径变量(内部/外部)。我们正在使用Spring FileCopyUtils工具类流从源复制到目的地。

配置

package com.yiibai.springmvc.configuration;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.yiibai.springmvc")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter{@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();viewResolver.setViewClass(JstlView.class);viewResolver.setPrefix("/WEB-INF/views/");viewResolver.setSuffix(".jsp");registry.viewResolver(viewResolver);}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("/static/");}}

初始化

package com.yiibai.springmvc.configuration;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[] { HelloWorldConfiguration.class };}@Overrideprotected Class<?>[] getServletConfigClasses() {return null;}@Overrideprotected String[] getServletMappings() {return new String[] { "/" };}}

添加视图

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Spring 4 MVC File Download Example</title><link href="<c:url value='/static/css/bootstrap.css' />"  rel="stylesheet"></link><link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
</head>
<body><div class="form-container"><h1>Welcome to FileDownloader Example</h1>Click on below links to see FileDownload in action.<br/><br/><a href="<c:url value='/download/internal' />">Download This File (located inside project)</a>  <br/><a href="<c:url value='/download/external' />">Download This File (located outside project, on file system)</a></div> 
</body>
</html>

构建,部署和运行应用程序

现在构建war(在前面的Eclipse教程)或通过Maven的命令行( mvn clean install)。部署 war 到Servlet3.0容器。或:

打开浏览器,浏览 http://localhost:8080/Spring4MVCFileDownloadExample

点击第二个链接。外部文件应被下载。

点击第一个链接。内部文件[这是一个PDF]应该显示在浏览器中,这是由于 Content-Disposition: inline. 通过内联,如果内容可以通过浏览器显示,它会显示它在浏览器中。

现在从内联更改内容处置备注。构建并部署。点击第一个链接。这个时候您应该看到 PDF文件被下载。

就这样,完成!

 

下载代码:http://pan.baidu.com/s/1c1lmeL6

转载于:https://www.cnblogs.com/jxldjsn/p/5671582.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/256812.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

学习笔记(54):Python实战编程-Scale

立即学习:https://edu.csdn.net/course/play/19711/343117?utm_sourceblogtoedu 1.滑块组件Scale: 用于定义一定范围的区间&#xff0c;如音量大小的调整就是滑块组件&#xff0c;这里是以滑动滑块来改变标签文字的大小为例进行说明的 2.知识点&#xff1a; 1&#xff09;滑…

不可不知的:iOS开发的22个诡异技巧

结合自身的实践开发经验总结出了22个iOS开发的小技巧&#xff0c;以非常欢乐的语调轻松解决开发过程中所遇到的各种苦逼难题&#xff0c;光读着便已忍俊不禁。 1. TableView不显示没内容的Cell怎么办&#xff1f; 类似于图1&#xff0c;我不想让下面的那些空显示。很简单&#…

linux删除之前的文件日志

linux下每天都在产生LOG日志文件&#xff0c;如果不定期删除&#xff0c;迟早挤爆硬盘&#xff0c;如果手动删除&#xff0c;几次可以&#xff0c;不是长久之计。这些事交给Linux系统就可以解决。 试验环境&#xff1a; 系统&#xff1a;CentOS 6.5 x64 测试路径、测试文件名、…

线程操作范例

实例要求&#xff1a; 设计一个线程操作类&#xff0c;要求可以产生三个线程对象&#xff0c;并可以分别设置三个线程的休眠时间。如下所示&#xff1a; 问怎么设计&#xff1f; 分析 从之前学习知道&#xff0c;线程的实现有两种方式&#xff0c;一种是继承Thread类&#xff0…

学习笔记(55):Python实战编程-Scrollbar

立即学习:https://edu.csdn.net/course/play/19711/343118?utm_sourceblogtoedu 1.滚动条ScrollBar&#xff1a; 当列表内容项的内容过多时&#xff0c;就需要使用到这个滚动条来进行拖动显示更多的其他选项&#xff1b;一般滚动条是和listbox配对使用的 2.注意事项&#xff…

【转】Unity3D研究院之使用Xamarin Studio调试Unity程序

如果你是在windows上开发&#xff0c;就无视这篇文章吧。 为什么要用Xamarin Studio 你可以看看我之前的文章 http://www.xuanyusong.com/archives/2683 unity4.x 和 unity5.x都可以用Xamarin Studio 来调试&#xff0c;亲测&#xff01; 先下载插件&#xff1a;http://files.u…

配置SMB共享 、 配置NFS共享

虚拟机&#xff0c;均要检测1. Yum是否可用2. 防火墙默认区域修改为trusted3. IP地址是否配置########################################################################################################### samba 文件共享&#xff08;共享文件夹&#xff09; Samba 软件…

stdout标准输出、stderr标准错误输出 标准输入、标准输出、标准错误输出分别被定义为0、1、2。

$ make > compile.log 2>&1 首先将标准错误输出也重定向到标准输出中&#xff0c;再将标准输出重定向到 compile.log 这个文件中。这样我们就可以将所有的输出都存储到文件中了。

centos7 和centos 6的一些区别

平时的我们基本都用CentOS 6 。但是偶尔遇到的就记录下来了&#xff0c;与大家分享。防火墙[CentOS 6] iptables[CentOS 7] firewalld在7中开启80端口 firewall-cmd --zonepublic --add-port80/tcp --permanent #出现success表明添加成功复制代码命令含义&#xff1a…

systemverilog 起步

转一篇Systemverilog的一个牛人总结&#xff1a; http://blog.sina.com.cn/s/blog_5e9b181a010188re.html 1、合并数组和非合并数组 1&#xff09;合并数组&#xff1a; 存储方式是连续的&#xff0c;中间没有闲置空间。 例如&#xff0c;32bit的寄存器&#xff0c;可以看成是4…

学习笔记(56):Python实战编程-Menu

立即学习:https://edu.csdn.net/course/play/19711/343119?utm_sourceblogtoedu 1.菜单menu: 1&#xff09;弹出式菜单&#xff0c;类似与电脑桌面右击弹出的菜单成为弹出菜单&#xff1b; 2&#xff09;窗体式菜单&#xff1a;类似于word上面的菜单栏 2.窗体菜单创建的步骤…

SystemCenter2012SP1实践(19)集成WSUS更新服务器2012

今天我们的任务是配置一台WSUS&#xff08;Windows更新服务器&#xff09;&#xff0c;以方便后期通过"基线"与其组合&#xff0c;完成虚拟机的系统补丁升级。WSUS是Windows系统运维自动化的一个重要组成部分&#xff0c;通过它&#xff0c;能够节省我们很多的运维时…

像元尺寸计算

像元尺寸 X 总像素大小 感光芯片尺寸&#xff08;图像区域大小&#xff09;

win7右键点击文件夹进入命令窗口方法

方法一&#xff1a;按住shift键&#xff0c;鼠标右击&#xff0c;会出现"在此处打开命令窗口"&#xff1b;方法二&#xff1a;修改注册表&#xff0c;为鼠标右键添加打开命令行功能&#xff1b;(1)将下列内容赋值到记事本中&#xff0c;并保存为.reg文件。Windows Re…

教你学会Linux/Unix下的vi文本编辑器

vi编辑器是Unix/Linux系统管理员必须学会使用的编辑器。看了不少关于vi的资料&#xff0c;终于得到这个总结。首先&#xff0c;记住vi编辑器的两个模式&#xff1a;1、命令模式2、编辑模式。在一个UNIX/Linux的shell命令或者一个以斜杠&#xff08;/&#xff09;、问号&#xf…

C++函数返回引用的含义

引用的意思就是说返回变量的地址而非变量本身。这样子函double数结束之后存储返回值的内存单元不会被销毁&#xff0c;保留了它的地址。 例如下面这个例子: int a1,b; ba; b; 这个例子里执行完之后a为1&#xff0c;而b为2。 但这个例子&#xff1a; int a1; int *b&#xff1b;…

LintCode: 3 Sum

C 把3个数求和&#xff0c;转变为2个数求和 1. 把数组排序 2. 注意过滤重复值 3. 从前到后遍历&#xff0c;游标i 4. 从后边数中找start &#xff0b; end &#xff1d; -arr[i]的2 sum 5. start &#xff0b; end < -arr[i], start 6. start end > -arr[i], end-- 7. s…

$* $@ $# $? $$ $! $0 $_

特殊参数&#xff1a; [xiluhuavm-xiluhua][~]$ set one two three  #使用set命令设置位置参数[xiluhuavm-xiluhua][~]$ echo $*        #打印所有位置参数 one two three[xiluhuavm-xiluhua][~]$ echo $        #打印所有位置参数 one two three[xiluhuavm-…

最优化课堂笔记03:整数规划

二、整数规划问题的求解方法&#xff1a;&#xff08;重点&#xff1a;分枝定界法&#xff09; 1.割平面法 1&#xff09;基本思想 2&#xff09;求解步骤 2&#xff09;重点&#xff1a;分枝定界法&#xff08;极大化的问题&#xff09;考试不会分很多次枝&#xff0c;用图解…