相关文章推荐
小胡子的沙发  ·  linux ...·  2 周前    · 
千年单身的充电器  ·  Will azur map is ...·  10 月前    · 
直爽的柑橘  ·  mysql ...·  10 月前    · 
springboot-实现文件下载与在线预览得骚操作

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", "\\");