本文介绍spring文件下载功能

目录结构

DemoApplication

package com.springlearn.learn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

WebConfig

package com.springlearn.learn.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration
public class WebConfig implements WebMvcConfigurer { @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
}

TestController

package com.springlearn.learn.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse; import com.springlearn.learn.utils.MediaTypeUtils; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; @RestController
public class TestController { @Autowired
private ServletContext servletContext; @ResponseBody
@RequestMapping(value = "/DownLoadTest", method = RequestMethod.GET)
public void Test(@RequestParam(defaultValue = "spring-boot-reference.pdf") String fileName, HttpServletResponse response) throws IOException {
MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName); System.out.println("fileName: " + fileName);
System.out.println("mediaType: " + mediaType); String filepath = "C:\\Users\\26401\\Desktop\\learn";
File file = new File(filepath + File.separator + fileName); response.setContentType(mediaType.getType());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName());
response.setContentLength((int) file.length()); BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
inStream.close();
}
}

MediaTypeUtils


package com.springlearn.learn.utils; import javax.servlet.ServletContext; import org.springframework.http.MediaType; public class MediaTypeUtils {
public static MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) {
String mineType = servletContext.getMimeType(fileName);
try {
MediaType mediaType = MediaType.parseMediaType(mineType);
return mediaType;
} catch (Exception e) {
return MediaType.APPLICATION_OCTET_STREAM;
}
} }

前端测试

直接访问 http://localhost:9001/DownLoadTest 即可

springboot成神之——spring文件下载功能的更多相关文章

  1. springboot成神之——spring的文件上传

    本文介绍spring的文件上传 目录结构 配置application DemoApplication WebConfig TestController 前端上传 本文介绍spring的文件上传 目录结 ...

  2. springboot成神之——spring jdbc的使用

    本文介绍spring jdbc的使用 目录结构 pom配置 properties配置 model层User类 Dao层QueryForListDao config层AppConfiguration 程 ...

  3. springboot成神之——spring boot,spring jdbc和spring transaction的使用

    本文介绍spring boot,spring jdbc和spring transaction的使用 项目结构 依赖 application model层 mapper层 dao层 exception层 ...

  4. springboot成神之——ioc容器(依赖注入)

    springboot成神之--ioc容器(依赖注入) spring的ioc功能 文件目录结构 lang Chinese English GreetingService MyRepository MyC ...

  5. springboot成神之——springboot入门使用

    springboot创建webservice访问mysql(使用maven) 安装 起步 spring常用命令 spring常见注释 springboot入门级使用 配置你的pom.xml文件 配置文 ...

  6. springboot成神之——mybatis和mybatis-generator

    项目结构 依赖 generator配置文件 properties配置 生成文件 使用Example 本文讲解如何在spring-boot中使用mybatis和mybatis-generator自动生成 ...

  7. springboot成神之——swagger文档自动生成工具

    本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...

  8. springboot成神之——mybatis在spring-boot中使用的几种方式

    本文介绍mybatis在spring-boot中使用的几种方式 项目结构 依赖 WebConfig DemoApplication 方式一--@Select User DemoApplication ...

  9. springboot成神之——监视器

    Spring Boot 的监视器 依赖 配置 书写监视控制器 常用的一些内置endpoint 定义actuator/info特殊endpoint actuator/shutdown需要post请求才能 ...

随机推荐

  1. Robocopy 一个文件后关机

    robocopy c:\folder \\192.168.1.10\shared somefile.dat & shutdown -s -t 30 -f 此例子复制c:\folder\some ...

  2. tracecaller.cs

    #region Utility #if TRACE private const string Traceformat = "\"{0}\",\"{1:yyyy- ...

  3. zzuli 2172 队列优化dp

    2172: GJJ的日常之购物 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 9  Solved: 8 SubmitStatusWeb Board De ...

  4. 在启动mysql的时候出现如下问题:“ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)”

    今天在启动Mysql 的时候出现如下的问题:“ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)” 在查询 ...

  5. LeetCode OJ:Pow(x, n) (幂运算)

    Implement pow(x, n). 幂运算,简单的方法snag然很好实现,直接循环相乘就可以了,但是这里应该不是那种那么简单,我的做法使用到了一点递归: class Solution { pub ...

  6. Android UID and PID

    Android UID and PID 我们经常在一个activity中去start另一个activity,或者与另一个acitivity的结果进行交互 (startActivityForResult ...

  7. 重读tcp-ip详解三卷:1

    应用层 Http.Telnet.FTP和e-mail等 负责把数据传输到传输层或接收从传输层返回的数据传输层 TCP和UDP 主要为两台主机上的应用程序提供端到端的通信,TCP为两台主机提供高可靠性的 ...

  8. 旧书重温:0day2【6】bind_shell

    学习了以上5节课,我们学到了很多知识,例如如何动态获取指定函数的地址:我们也学到了很多经验,例如如何发现代码中的错误,如何用od定位到错误,并修正. 有了以上积累,今天我们继续实验bind_shell ...

  9. 一个高性能RPC框架原理剖析

    业务与底层网络通信分离 Server大部分主要分为两层: 网络接收层:负责监听端口,负责收包,编码,解码工作,负责将响应包回传给客户端. 业务处理层:负责接收网络接收层完整的包,如果是RPCserve ...

  10. 【vs2013】如何在VS的MFC中配置使用GDI+?

    摘自:http://www.cnblogs.com/CSGrandeur/p/3156843.html (已实验,可行) 1.配置GDI+ VS2010自带GDI+,直接使用. (1)首先要添加头文件 ...