Spring Boot入门(11)实现文件下载功能
在这篇博客中,我们将展示如何在Spring Boot中实现文件的下载功能。
还是遵循笔者写博客的一贯风格,简单又不失详细,实用又能让你学会。
本次建立的Spring Boot项目的主要功能为文件下载,而且这也是唯一功能,当然,作为例子,要尽可能简单,所以,功能简化为只下载E盘music_eg目录下的某一个文件。
该Spring Boot项目的名称为file_download,其具体结构如下:
build.gradle文件的代码如下:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
我们只需要创建一个控制器(Controler)文件,即Controller目录下的File_Download.java,其完整目录如下:
package com.example.file_download.Controller;
import java.io.*;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class File_Download {
//实现Spring Boot 的文件下载功能,映射网址为/download
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
// 获取指定目录下的第一个文件
File scFileDir = new File("E://music_eg");
File TrxFiles[] = scFileDir.listFiles();
System.out.println(TrxFiles[0]);
String fileName = TrxFiles[0].getName(); //下载的文件名
// 如果文件名不为空,则进行下载
if (fileName != null) {
//设置文件路径
String realPath = "E://music_eg/";
File file = new File(realPath, fileName);
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
}
catch (Exception e) {
System.out.println("Download the song failed!");
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
这样我们就完成了Spring Boot的文件下载功能。什么?这样就搞定了?是的,就是这么简单,因为只实现了文件下载功能。具体的代码留给读者好好分析哦~~
写完代码并不是我们的最终目的,我们还差最后一步,那就是测试!测试,真的相当重要啊~
运行Spring Boot项目后,在浏览器中输入:http://localhost:8080/download , 你会发现什么?那就是你的浏览器已经开始下载E盘music_eg目录下的某一个文件啦(前提是E盘中存在music_eg目录,当然里面还得有文件,本例仅作为测试),如下图所示:
我们再去查看E盘music_eg目录,如下:
So, 用Spring Boot实现文件下载功能搞定!欢迎大家交流哦~
注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~
关注公众号
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
Python数据持久化-MongoDB篇
2018年7月6日笔记 下文中的操作都是使用python操作mongoDB,所以前提是必须安装python和mongoDB。 1. 安装pymongo 在cmd或者PowerShell中运行命令:pip install pymongo 2. 插入数据 2.1 插入一条数据 引入pymongo库中的MongoClient类,使用该类的初始化方法实例化一个对象赋值给conn conn.myschool为数据库school,将其赋值给变量db db.students为数据库school中的students集合,将其赋值给变量students 定义一个数据类型为字典dict的变量zhangsan 往数据库中的students集合中插入zhangsan的信息文档,students.insert_one(zhangsan) from pymongo import MongoClient if __name__ == '__main__': conn = MongoClient('localhost') db = conn.myschool students = db.students zhangs...
-
下一篇
第3章—高级装配—运行时注入
运行时注入 当我们经常用如下的硬解码方式来配置文件: <bean id="SgtPeppers" class="com.CDDemo.SgtPeppers" p:title="sgt" p:song="Twinkle, twinkle, little start"> <property name="title" value="sgt"/> <property name="song" value="Twinkle, twinkle, little start"/> </bean> 但有时我们需要避免硬解码,需要想要这些值在运行时确定,Spring提供了两种在运行时求值的方式: 属性占位符 Spring表达式语言(SpEL) 1.注入外部的值 在Spring中,处理外部值得最简单方式就是申明属性源并通过Spring的Enviroment来检索属性.例如: @Configuration @PropertySource("classpath:app.properties") public class ExpressionTest { @Aut...
相关文章
文章评论
共有0条评论来说两句吧...

微信收款码
支付宝收款码