本文介绍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. LeetCode OJ:Combination Sum II (组合之和 II)

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. Linux安全运维笔记2018-03-01更新

    本人wechat:YWNlODAyMzU5MTEzMTQ=. *** # 修改关键目录文件的权限 chmod u-x,g-r /home/lema chmod 444 /home/lema # 用户权 ...

  3. Python label for _ 用法

    Python label for _ 用法 Python label for _ 用法 >>> label_data = [iter([3,4]),iter([4,9]), iter ...

  4. Arcgis for Js之GeometryService实现测量距离和面积

    距离和面积的测量时GIS常见的功能,在本节,讲述的是通过GeometryService实现测量面积和距离.先看看实现后的效果:                                  距离 ...

  5. 关于this指向问题的总结【转自秘密花园】

    this 的工作原理 JavaScript 有一套完全不同于其它语言的对 this 的处理机制. 在五种不同的情况下 ,this 指向的各不相同. 第一种:全局范围内 this; 当在全部范围内使用  ...

  6. 数据库连接配置 app.config web.config

    通过ADO.Net连接程序和SQLServer数据库的连接字符串: connectionString ="server=(local);database=Demo;integrated se ...

  7. Python reload() 函数

    reload(module) 作用: 用于重新载入之前载入的模块. module -- 模块对象.返回模块对象. 实例:  重新载入 sys 模块,并设置默认编码为 utf8 >>> ...

  8. 浪潮各机型管理芯片BMC IP(智能平台管理接口)设置

    NF5240m3/NF5140m3/NF5280m3/SA5212H2/NP5540M3NF5270M3/NF5170M3/NF8420m3 IPMI主板集成管理芯片BMC IP 设置开机按DEL键进 ...

  9. 在android开发中添加外挂字体

    1.在项目目录中,右键app——New——Folder—— Assets Folder 2.把.ttf或者.oft文件拷进这个assets文件夹 3.在onCreate()中 Typeface typ ...

  10. Dobbo问题及解决方案:forbid-consumer

    本地运行Dubbo经常出现以下情况: com.alibaba.dubbo.rpc.RpcException: Forbid consumer 10.0.53.69 access service com ...