本文介绍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. POJ 1062 限制点

    http://poj.org/problem?id=1062 昂贵的聘礼 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 50 ...

  2. 关于shortcut icon和icon代码的区别介绍

    语句一:<link rel="shortcut icon" href="favicon.ico" /> 语句二:<link rel=" ...

  3. python---迭代器与生成器(一)

    迭代器与生成器 迭代器 迭代是Python最强大的功能之一,是访问集合元素的一种方式.. 迭代器是一个可以记住遍历的位置的对象. 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束.迭代 ...

  4. 25-THREE.JS 绘制线框样式几何图形的材质 线材质

    <!DOCTYPE html> <html> <head> <title></title> <script src="htt ...

  5. iframe框架

    在一个页面里做一个区域引入另一个页面的方法: <a href="http://www.baidu.com" target="in">百度</a ...

  6. input type=file 怎么样调取用户手机照相机

    input 有个属性accept="image/*" 这样就可以了,同时在网上看到了其他答案,试了下没啥效果.写记录下来 如下: 使用input:file标签, 去调用系统默认相机 ...

  7. OC-通知+Block

    =================================== 一.通知(NSNotification) NSNotification 通知类,这个类中有 NSNotificationCent ...

  8. c# unicode 编码 中文转换 已测试(转)

    中文传参时因为编码不同经常凌乱风中,故传前编成unicode码来过度是一个不错的解决方法 /// <summary> /// 中文转unicode        /// </summ ...

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

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

  10. 软件测试 Record

    fxcopnunit软件质量 EDW 数据仓库ETL KPI 敏捷 测试计划 单元测试 集成测试 系统测试 对测试结果 阶段性 分析 总结 测试结果报告 环境问题:软硬件用户有问题,我们这边没有有效问 ...