Spring MVC 4 文件下载实例(带源码)

【本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看。源码下载地址在文章末尾。】

【翻译 by 明明如月 QQ 605283073】

原文地址:http://websystique.com/springmvc/spring-mvc-4-file-download-example/

上一篇:Spring
MVC 4 使用常规的fileupload上传文件(带源码)

本文将为你展示通过Spring MVC 4实现文件下载。

下载一个文件比较简单,主要包括下面几个步骤.

  • 创建下载文件的InputStream(输入流)
  • 找到下载文件类型的MIME
    type
     .

    – 可能是 application/pdf, text/html,application/xml,image/png, ..或者其他类型.

  • 在response(HttpServletResponse)中设置  Content-Type
    为上面的值
    .

    response.setContentType(mimeType);

  • 设置Content
    length
     文件长度.

    response.setContentLength(file.getLength());//字节长度

  • 在响应中设置Content-Disposition HEADER 

    response.setHeader(“Content-Disposition”, “attachment; filename=” + fileName); //With ‘attachement’ File will be downloaded
    as is. 可能会显示基于浏览器的 ‘文件另存为’对话框.

    response.setHeader(“Content-Disposition”, “inline; filename=” + fileName);//With ‘inline’ browser will try to display content
    right into broswer for certain contents(imgages,PDF,text,..). 其他内容文件将直接被下载

  • 拷贝 InputStream(输入流)的字节到 response的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.websystique.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-compiler-plugin</artifactId>
					<version>3.2</version>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
				</plugin>
				<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.websystique.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());
	}

}

配置

package com.websystique.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.websystique.springmvc")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter{

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

}

初始化

package com.websystique.springmvc.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { HelloWorldConfiguration.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected 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>

构建发布和运行

在tomcat里面发布运行

浏览器输入 http://localhost:8080/Spring4MVCFileDownloadExample

点击第二个超链接 将下载外部(项目外)文件

点击第一个超链接.
内部(项目内部)文件 [一个 PDF] 将在浏览器中显示, 如果能在浏览器能够显示就会被显示在浏览器里面。

把Content-Disposition
从inline设置为 attachment.构建并重新发布 点第一个链接,PDF将被下载下来。

项目下载:http://websystique.com/?smd_process_download=1&download_id=1769

时间: 2024-12-13 16:05:06

Spring MVC 4 文件下载实例(带源码)的相关文章

spring MVC cors跨域实现源码解析 CorsConfiguration UrlBasedCorsConfigurationSource

spring MVC cors跨域实现源码解析 名词解释:跨域资源共享(Cross-Origin Resource Sharing) 简单说就是只要协议.IP.http方法任意一个不同就是跨域. spring MVC自4.2开始添加了跨域的支持. 跨域具体的定义请移步mozilla查看 使用案例 spring mvc中跨域使用有3种方式: 在web.xml中配置CorsFilter <filter> <filter-name>cors</filter-name> <

Spring MVC 4使用Servlet 3 MultiPartConfigElement实现文件上传(带源码)

[本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看.源码下载地址在文章末尾.] [翻译 by 明明如月 QQ 605283073] 原文地址:http://websystique.com/springmvc/spring-mvc-4-file-upload-example-using-multipartconfigelement/ 上一篇:Spring MVC 4 使用常规的fileupload上传文件(带源码) 下一篇:Spring MVC 4 文件下载实例(带源码)

Spring 4 MVC 视图解析器(XML JSON PDF等) 纯注解(带源码)【推荐】

原文地址:http://websystique.com/springmvc/spring-4-mvc-contentnegotiatingviewresolver-example/ [本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看.源码下载地址在文章末尾.] [翻译 by 明明如月 QQ 605283073] 下一篇:Spring 4 MVC @RestController 注解实现REST Service 上一篇:Spring 4 MVC 表单校验资源处理(带源码)

spring mvc+ibatis+mysql的组合框架入门实例demo源码下载

原文:spring mvc+ibatis+mysql的组合框架入门实例demo源码下载 源代码下载地址:http://www.zuidaima.com/share/1550463678958592.htm spring mvc+ibatis+mysql的组合框架实例 首页 http://localhost:端口/项目/index.jsp 添加用户 添加地址 项目截图 jar包截图

Spring MVC 4 RESTFul Web Services CRUD例子(带源码)【这才是restful,超经典】

[本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看.源码下载地址在文章末尾.] [翻译 by 明明如月 QQ 605283073] 原文地址:http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/ 上一篇: Spring 4 MVC @RestController 注解实现REST Service 下一篇:Spring MVC 4 文件上传

Spring MVC 4 使用常规的fileupload上传文件(带源码)

[本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看.源码下载地址在文章末尾.] [翻译 by 明明如月 QQ 605283073] 上一篇: Spring MVC 4 文件上传下载 Hibernate+MySQL例子 (带源码) 原文地址:http://websystique.com/springmvc/spring-mvc-4-file-upload-example-using-commons-fileupload/ 本文将实现使用SpringMultipartRes

Spring 4 MVC 表单校验资源处理(带源码)

[本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看] [翻译 by 明明如月 QQ 605283073] 上一篇:Spring 4 MVC HelloWorld 纯注解方式(带源码) 下一篇文章:Spring 4 MVC 视图解析器(XML JSON PDF等) 纯注解 #项目下载地址:http://websystique.com/?smd_process_download=1&download_id=1258# 本文我们将学习使用Spring 表单标签( Spring

Spring 4 MVC @RestController 注解实现REST Service(带源码)

原文地址:http://websystique.com/springmvc/spring-4-mvc-rest-service-example-using-restcontroller/ [本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看.源码下载地址在文章末尾.] [翻译 by 明明如月 QQ 605283073] 上一篇:Spring 4 MVC 视图解析器(XML JSON PDF等) 纯注解 下一篇:Spring MVC 4 RESTFul Web Servic

Spring 4 MVC HelloWorld 纯注解方式(带源码)【超赞】

[本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看] [翻译 by 明明如月 QQ 605283073] #项目下载地址:http://websystique.com/?smd_process_download=1&download_id=1722#. 上一篇:Spring 4 MVC hello world 教程-完全基于XML(带项目源码) 下一篇: Spring 4 MVC 表单校验资源处理(带源码) 在上一个例子:Spring 4 MVC hello world