码迷,mamicode.com
首页 > 编程语言 > 详细

spring4 文件下载功能

时间:2016-08-05 19:31:49      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

需要准备的工具和框架

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

文件结构如下

技术分享

设置依赖包

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>com.gome.springmvc</groupId>
 5   <artifactId>Spring4MVCFileDownloadExample</artifactId>
 6   <packaging>war</packaging>
 7   <version>1.0.0</version>
 8   <name>Spring4MVCFileDownloadExample Maven Webapp</name>
 9   
10   
11      <properties>
12         <springframework.version>4.2.0.RELEASE</springframework.version>
13     </properties>
14  
15     <dependencies>
16         <dependency>
17             <groupId>org.springframework</groupId>
18             <artifactId>spring-webmvc</artifactId>
19             <version>${springframework.version}</version>
20         </dependency>
21  
22         <dependency>
23             <groupId>javax.servlet</groupId>
24             <artifactId>javax.servlet-api</artifactId>
25             <version>3.1.0</version>
26         </dependency>
27         <dependency>
28             <groupId>javax.servlet</groupId>
29             <artifactId>jstl</artifactId>
30             <version>1.2</version>
31         </dependency>
32     </dependencies>
33  
34  
35     <build>
36         <pluginManagement>
37             <plugins>
38                 <plugin>
39                     <groupId>org.apache.maven.plugins</groupId>
40                     <artifactId>maven-compiler-plugin</artifactId>
41                     <version>3.2</version>
42                     <configuration>
43                         <source>1.7</source>
44                         <target>1.7</target>
45                     </configuration>
46                 </plugin>
47                 <plugin>
48                     <groupId>org.apache.maven.plugins</groupId>
49                     <artifactId>maven-war-plugin</artifactId>
50                     <version>2.4</version>
51                     <configuration>
52                         <warSourceDirectory>src/main/webapp</warSourceDirectory>
53                         <warName>Spring4MVCFileDownloadExample</warName>
54                         <failOnMissingWebXml>false</failOnMissingWebXml>
55                     </configuration>
56                 </plugin>
57             </plugins>
58         </pluginManagement>
59  
60         <finalName>Spring4MVCFileDownloadExample</finalName>
61     </build>
62 </project>

 

controller实现

package com.gome.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());
    }
 
}

 

文件下载中需要注意的几个问题

1. 文件存储路径应该做混淆,防止从过猜测url等参数尝试获得其他文件

2. 除了对参数校验,还要对将下载的文件绝对路径、类型校验。

3. 白名单策略,只有规定路径下,规定类型、拥有规定权限的人才可以下载。

 

spring4 文件下载功能

标签:

原文地址:http://www.cnblogs.com/easyroom/p/5742334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!