springboot-實現文件下載


一 前言

本文實現的文件下載是使用Apache 的 commons-fileupload 實現;在之前的springboot系列文件中已經講述過如何實現多文件上傳;這篇文件實現的文件下載功能主要是能在瀏覽器在線預覽或者下載至本地;

二 pom依賴

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>
	 <dependencies>
	        <dependency>
	            <groupId>commons-fileupload</groupId>
	            <artifactId>commons-fileupload</artifactId>
	            <version>1.3.3</version>
	        </dependency>
	        <dependency>
	            <groupId>org.springframework.boot</groupId>
	            <artifactId>spring-boot-starter-web</artifactId>
	        </dependency>
	    </dependencies>
    

三 文件下載示例

參數 path 表示相對於根路徑的相對路徑
參數userAgent 是為了兼容IE判斷,如果使用谷歌,火狐瀏覽器就可以省略這個參數;
參數 filename 表示你下載至本地的文件名;
參數 inline表示是否要在線瀏覽,true是,false否;

/**
 * @Author lsc
 * @Description <p> 文件下載</p>
 * @Date 2019/11/20 11:54
 */
@RestController
@RequestMapping("file")
public class DownloadController {
	// 下載文件的根路徑
    private String downloadPath = "C:\\mydata\\generator";

    @GetMapping("download")
    public ResponseEntity<byte[]> downlaodFile(HttpServletRequest request, @RequestParam("path") String path
            , @RequestHeader("user-agent") String userAgent, @RequestParam("filename") String filename
            ,@RequestParam(required = false,defaultValue = "false") boolean inline ) {
		// 根路徑加上傳參數的路徑構成文件路徑地址
        String realPath = downloadPath + path;
        File file = new File(realPath);
        // 構建響應
        ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok();
        bodyBuilder.contentLength(file.length());
        // 二進制數據流
        bodyBuilder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        // 文件名編碼
        try {
            String encodeFileName = URLEncoder.encode(filename, "UTF-8");
            // IE
            if (userAgent.indexOf("MSIE")>0){
                bodyBuilder.header("Content-Disposition","attachment;filename="+encodeFileName);
            }else {
                // 其他瀏覽器
                if (inline){
                    // 在瀏覽器中打開
                    URL url = new URL("file:///" + file);
                    bodyBuilder.header("Content-Type",url.openConnection().getContentType());
                    bodyBuilder.header("Content-Disposition","inline;filename*=UTF-8''"+encodeFileName);
                }else {
                    // 直接下載
                    bodyBuilder.header("Content-Disposition","attachment;filename*=UTF-8''"+encodeFileName);
                }

            }
            // 下載成功返回二進制流
             return bodyBuilder.body(FileUtils.readFileToByteArray(file));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        // 下載失敗直接返回錯誤的請求
        return (ResponseEntity<byte[]>) ResponseEntity.badRequest();

    }

}

四 tomcat配置

主要是開發特殊字符斜桿,如果是在linux上開發,那就自定義路徑,這個步驟可以省略;

@Configuration
public class ServerConfig {

    //Url路徑添加支持字符
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        //設置Tomcate 支持
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector connector) {
                connector.setProperty("relaxedQueryChars", "\\");
            }
        });
        return factory;
    }

}

五 瀏覽器測試

下載路徑
http://localhost:8080/file/download?path=\2019\11\c7ed67a6-5502-479b-8934-736021426236.jpg&filename=5555.jpg

生成結果
在這里插入圖片描述

六 源碼

github : youku1327

在這里插入圖片描述

本套教程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM