1. 文件就保存在本地,可以用 new File()来获取文件
2. 文件保存在FTP服务器上,可以使用ftpClient.retrieveFile(remotePath,outputStream)
项目中经常用到播放一些文件,比如mp3,wav格式的一些文件,下面提供了一种直接拿到音频文件并响应给前端的一种方式,我的音频文件是存在ftp服务器上,而且ftp服务器和应用服务器是部署在一起的,文件要从ftp服务器上获取,这个可以根据实际存放的地方去拿文件。经过测试,前端只需要 <audio>标签接收就可以了,src路径直接填写接口路径,话不多说,直接上图:
1. 文件就保存在本地,可以用 new File()来获取文件
File music = new File("C:\Users\Temp\a.mp3");
import io.swagger.annotations.ApiImplicitParam;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
@RequestMapping("/stream")
public class WavApiController {
@Value("${ftpServer_url}")
private String ftpServer_url;
@Value("${ftpServer_audio_url}")
private String ftpServer_audio_url;
@RequestMapping("/mp3")
@ApiImplicitParam(name = "voiceName", value = "音频文件名", paramType = "query", required = true, dataType = "String")
public void wavStream(HttpServletRequest request, HttpServletResponse response, String voiceName){
String database = ftpServer_url+ftpServer_audio_url;//音频文件所在的文件夹路径
// 文件目录(偷懒没有改变量,名称,此处和FTP没关系,就是文件的绝对路径)
// 也就是 File music = new File("C:\Users\Administrator\AppData\Local\Temp\a.mp3");
File music = new File(database+voiceName);
if (!music.exists()){
System.out.println(database+"不存在 文件名为:"+voiceName+"的音频文件!");
String range=request.getHeader("Range");
//开始下载位置
long startByte = 0;
//结束下载位置
long endByte = music.length() - 1;
//有range的话
if (range != null && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String ranges[] = range.split("-");
try {
//判断range的类型
if (ranges.length == 1) {
//类型一:bytes=-2343
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
//类型二:bytes=2343-
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
//类型三:bytes=22-2343
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
} catch (NumberFormatException e) {
startByte = 0;
endByte = music.length() - 1;
//要下载的长度
long contentLength = endByte - startByte + 1;
//文件名
String fileName = music.getName();
//文件类型
String contentType = request.getServletContext().getMimeType(fileName);
//各种响应头设置
//参考资料:https://www.ibm.com/developerworks/cn/java/joy-down/index.html
//坑爹地方一:看代码
response.setHeader("Accept-Ranges", "bytes");
//坑爹地方二:http状态码要为206
response.setStatus(206);
response.setContentType(contentType);
response.setHeader("Content-Type", contentType);
//这里文件名换你想要的,inline表示浏览器直接实用(我方便测试用的)
//参考资料:http://hw1287789687.iteye.com/blog/2188500
// response.setHeader("Content-Disposition", "inline;filename=test.mp3");
response.setHeader("Content-Length", String.valueOf(contentLength));
//坑爹地方三:Content-Range,格式为
// [要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + music.length());
BufferedOutputStream outputStream = null;
RandomAccessFile randomAccessFile = null;
//已传送数据大小
long transmitted = 0;
try {
randomAccessFile = new RandomAccessFile(music, "r");
outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[4096];
int len = 0;
randomAccessFile.seek(startByte);
//坑爹地方四:判断是否到了最后不足4096(buff的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//不然会会先读取randomAccessFile,造成后面读取位置出错,找了一天才发现问题所在
while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
outputStream.write(buff, 0, len);
transmitted += len;
//停一下,方便测试,用的时候删了就行了
Thread.sleep(10);
//处理不足buff.length部分
if (transmitted < contentLength) {
len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
outputStream.write(buff, 0, len);
transmitted += len;
outputStream.flush();
response.flushBuffer();
randomAccessFile.close();
System.out.println("下载完毕:" + startByte + "-" + endByte + ":" + transmitted);
} catch (ClientAbortException e) {
System.out.println("用户停止下载:" + startByte + "-" + endByte + ":" + transmitted);
//捕获此异常表示拥护停止下载
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
2. 文件保存在FTP服务器上,可以使用ftpClient.retrieveFile(remotePath,outputStream)
ftpClient.retrieveFile(remotePath,outputStream);// 从FTP服务器上读取文件并写入到临时文件中
2.1 上面介绍的是一直文件绝对路径的情况,传文件路径过去就可以,但是经常我们的音频,视频文件是单独存放在像TFP服务器这样的Server上,我们以FTP为例,改一下上面的代码:
import io.swagger.annotations.ApiImplicitParam;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
@RequestMapping("/stream")
public class WavApiController {
@RequestMapping("/mp3")
@ApiImplicitParam(name = "remotePath", value = "FTP服务器上的路径+文件名", paramType = "query", required = true, dataType = "String")
* 本地FTP服务器:D:/FtpServer
* ---D:/FtpServer
* ------mp3(此文件夹下有文件 myMusic.mp3)
* ------txt(此文件夹下没有文件)
* -----------myMusic.mp3
* remotePath传值为:mp3/myMusic.mp3
public void wavStream(HttpServletRequest request, HttpServletResponse response, String remotePath){
//========================区别-start ================================
File music = null;
try {
music = File.createTempFile("tmp", remotePath.substring(remotePath.lastIndexOf(".")));
OutputStream ops= new FileOutputStream(music);
Boolean isSucccess = FtpUtil.retrieveFile(remotePath, ops);
System.out.println("=====写入临时文件成功与否:====" + isSucccess);
} catch (IOException e) {
e.printStackTrace();
//========================区别-end ================================
if (!music.exists()){
System.out.println(database+"不存在 文件名为:"+remotePath+"的音频文件!");
String range=request.getHeader("Range");
//开始下载位置
long startByte = 0;
//结束下载位置
long endByte = music.length() - 1;
//有range的话
if (range != null && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String ranges[] = range.split("-");
try {
//判断range的类型
if (ranges.length == 1) {
//类型一:bytes=-2343
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
//类型二:bytes=2343-
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
//类型三:bytes=22-2343
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
} catch (NumberFormatException e) {
startByte = 0;
endByte = music.length() - 1;
//要下载的长度
long contentLength = endByte - startByte + 1;
//文件名
String fileName = music.getName();
//文件类型
String contentType = request.getServletContext().getMimeType(fileName);
//各种响应头设置
//参考资料:https://www.ibm.com/developerworks/cn/java/joy-down/index.html
//坑爹地方一:看代码
response.setHeader("Accept-Ranges", "bytes");
//坑爹地方二:http状态码要为206
response.setStatus(206);
response.setContentType(contentType);
response.setHeader("Content-Type", contentType);
//这里文件名换你想要的,inline表示浏览器直接实用(我方便测试用的)
//参考资料:http://hw1287789687.iteye.com/blog/2188500
// response.setHeader("Content-Disposition", "inline;filename=test.mp3");
response.setHeader("Content-Length", String.valueOf(contentLength));
//坑爹地方三:Content-Range,格式为
// [要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + music.length());
BufferedOutputStream outputStream = null;
RandomAccessFile randomAccessFile = null;
//已传送数据大小
long transmitted = 0;
try {
randomAccessFile = new RandomAccessFile(music, "r");
outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[4096];
int len = 0;
randomAccessFile.seek(startByte);
//坑爹地方四:判断是否到了最后不足4096(buff的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//不然会会先读取randomAccessFile,造成后面读取位置出错,找了一天才发现问题所在
while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
outputStream.write(buff, 0, len);
transmitted += len;
//停一下,方便测试,用的时候删了就行了
Thread.sleep(10);
//处理不足buff.length部分
if (transmitted < contentLength) {
len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
outputStream.write(buff, 0, len);
transmitted += len;
outputStream.flush();
response.flushBuffer();
randomAccessFile.close();
System.out.println("下载完毕:" + startByte + "-" + endByte + ":" + transmitted);
} catch (ClientAbortException e) {
System.out.println("用户停止下载:" + startByte + "-" + endByte + ":" + transmitted);
//捕获此异常表示拥护停止下载
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
2.2 附上Ftp工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.zdhs.atw.common.utils._DateUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.pool2.ObjectPool;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;
import lombok.extern.slf4j.Slf4j;
* Ftp工具类
@Slf4j
public class FtpUtil {
* ftpClient连接池初始化标志
private static volatile boolean hasInit = false;
* ftpClient连接池
private static ObjectPool<FTPClient> ftpClientPool;
* 初始化ftpClientPool
* @param ftpClientPool
public static void init(ObjectPool<FTPClient> ftpClientPool) {
if (!hasInit) {
synchronized (FtpUtil.class) {
if (!hasInit) {
FtpUtil.ftpClientPool = ftpClientPool;
hasInit = true;
// /**
// * 读取csv文件
// *
// * @param remoteFilePath 文件路径(path+fileName)
// * @param header 列头
// * @return
// * @throws IOException
// */
// public static List<CSVRecord> readCsvFile(String remoteFilePath, String... headers) throws IOException {
// FTPClient ftpClient = getFtpClient();
// try (InputStream in = ftpClient.retrieveFileStream(encodingPath(remoteFilePath))) {
// return CSVFormat.EXCEL.withHeader(headers).withSkipHeaderRecord(false)
// .withIgnoreSurroundingSpaces().withIgnoreEmptyLines()
// .parse(new InputStreamReader(in, "utf-8")).getRecords();
// } finally {
// ftpClient.completePendingCommand();
// releaseFtpClient(ftpClient);
// }
// }
* 按行读取FTP文件
* @param remoteFilePath 文件路径(path+fileName)
* @return
* @throws IOException
public static List<String> readFileByLine(String remoteFilePath) throws IOException {
FTPClient ftpClient = getFtpClient();
try (InputStream in = ftpClient.retrieveFileStream(encodingPath(remoteFilePath));
BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
return br.lines().map(line -> StringUtils.trimToEmpty(line))
.filter(line -> StringUtils.isNotEmpty(line)).collect(Collectors.toList());
} finally {
ftpClient.completePendingCommand();
releaseFtpClient(ftpClient);
* 获取指定路径下FTP文件
* @param remotePath 路径
* @return FTPFile数组
* @throws IOException
public static FTPFile[] retrieveFTPFiles(String remotePath) throws IOException {
FTPClient ftpClient = getFtpClient();
try {
return ftpClient.listFiles(encodingPath(remotePath + "/"),
file -> file != null && file.getSize() > 0);
} finally {
releaseFtpClient(ftpClient);
* 获取指定路径下FTP文件 并 写入临时文件的outputStream中
* @param remotePath
* @param outputStream
* @return
* @throws IOException
public static Boolean retrieveFile(String remotePath, OutputStream outputStream) throws IOException {
FTPClient ftpClient = getFtpClient();
try {
return ftpClient.retrieveFile(remotePath,outputStream);
} finally {
releaseFtpClient(ftpClient);
* 获取指定路径下FTP文件名称
* @param remotePath 路径
* @return ftp文件名称列表 和 文件操作时间
* @throws IOException
public static Map<String, Date> retrieveFileNames(String remotePath) throws IOException {
Map<String, Date> files = new HashMap<>();
FTPFile[] ftpFiles = retrieveFTPFiles(remotePath);
if (ArrayUtils.isEmpty(ftpFiles)) {
return new HashMap<>();
//防止中文乱码
for (FTPFile ftpFile:ftpFiles) {
String fileName = new String(ftpFile.getName().getBytes("iso-8859-1"), "gb2312");
Calendar fileTime = ftpFile.getTimestamp();
Date date = fileTime.getTime();
//Date 类型转换为 String 类型
String time = _DateUtils.dateFormatToSecond(date);
files.put(fileName,date);
return files;
* 编码文件路径
private static String encodingPath(String path) throws UnsupportedEncodingException {
// FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码
return new String(path.replaceAll("//", "/").getBytes("GBK"), "iso-8859-1");
* 获取ftpClient
* @return
private static FTPClient getFtpClient() {
checkFtpClientPoolAvailable();
FTPClient ftpClient = null;
Exception ex = null;
// 获取连接最多尝试3次
for (int i = 0; i < 3; i++) {
try {
ftpClient = ftpClientPool.borrowObject();
ftpClient.changeWorkingDirectory("/");
break;
} catch (Exception e) {
ex = e;
if (ftpClient == null) {
throw new RuntimeException("Could not get a ftpClient from the pool", ex);
return ftpClient;
* 释放ftpClient
private static void releaseFtpClient(FTPClient ftpClient) {
if (ftpClient == null) {
return;
try {
ftpClientPool.returnObject(ftpClient);
} catch (Exception e) {
log.error("Could not return the ftpClient to the pool", e);
// destoryFtpClient
if (ftpClient.isAvailable()) {
try {
ftpClient.disconnect();
} catch (IOException io) {
* 检查ftpClientPool是否可用
private static void checkFtpClientPoolAvailable() {
Assert.state(hasInit, "FTP未启用或连接失败!");
* 上传Excel文件到FTP
* @param workbook
* @param remoteFilePath
* @throws IOException
public static boolean uploadExcel2Ftp(Workbook workbook, String remoteFilePath)
throws IOException {
Assert.notNull(workbook, "workbook cannot be null.");
Assert.hasText(remoteFilePath, "remoteFilePath cannot be null or blank.");
FTPClient ftpClient = getFtpClient();
try (OutputStream out = ftpClient.storeFileStream(encodingPath(remoteFilePath))) {
workbook.write(out);
workbook.close();
return true;
} finally {
ftpClient.completePendingCommand();
releaseFtpClient(ftpClient);
* 从ftp下载excel文件
* @param remoteFilePath
* @param response
* @throws IOException
public static void downloadExcel(String remoteFilePath, HttpServletResponse response)
throws IOException {
String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
FTPClient ftpClient = getFtpClient();
try (InputStream in = ftpClient.retrieveFileStream(encodingPath(remoteFilePath));
OutputStream out = response.getOutputStream()) {
int size = 0;
byte[] buf = new byte[10240];
while ((size = in.read(buf)) > 0) {
out.write(buf, 0, size);
out.flush();
} finally {
ftpClient.completePendingCommand();
releaseFtpClient(ftpClient);
2.3 把FTPConfiguration 连接,登录也贴出来
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PreDestroy;
@Slf4j
@Configuration
@ConditionalOnClass({GenericObjectPool.class, FTPClient.class})
@ConditionalOnProperty(value = "ftp.enabled", havingValue = "true")
@EnableConfigurationProperties(FTPConfiguration.FtpConfigProperties.class)
public class FTPConfiguration {
private ObjectPool<FTPClient> pool;
public FTPConfiguration(FtpConfigProperties props) {
// 默认最大连接数与最大空闲连接数都为8,最小空闲连接数为0
// 其他未设置属性使用默认值,可根据需要添加相关配置
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setMinEvictableIdleTimeMillis(60000);
poolConfig.setSoftMinEvictableIdleTimeMillis(50000);
poolConfig.setTimeBetweenEvictionRunsMillis(30000);
pool = new GenericObjectPool<>(new FtpClientPooledObjectFactory(props), poolConfig);
preLoadingFtpClient(props.getInitialSize(), poolConfig.getMaxIdle());
// 初始化ftp工具类中的ftpClientPool
FtpUtil.init(pool);
* 预先加载FTPClient连接到对象池中
* @param initialSize 初始化连接数
* @param maxIdle 最大空闲连接数
private void preLoadingFtpClient(Integer initialSize, int maxIdle) {
if (initialSize == null || initialSize <= 0) {
return;
int size = Math.min(initialSize.intValue(), maxIdle);
for (int i = 0; i < size; i++) {
try {
pool.addObject();
} catch (Exception e) {
log.error("preLoadingFtpClient error...", e);
@PreDestroy
public void destroy() {
if (pool != null) {
pool.close();
log.info("销毁ftpClientPool...");
* Ftp配置属性类,建立ftpClient时使用
@Data
@ConfigurationProperties(prefix = "ftp")
static class FtpConfigProperties {
private String host;
private int port;
private String username;
private String password;
private int bufferSize = 8096;
* 初始化连接数
private Integer initialSize = 0;
* FtpClient对象工厂类
static class FtpClientPooledObjectFactory implements PooledObjectFactory<FTPClient> {
private FtpConfigProperties props;
public FtpClientPooledObjectFactory(FtpConfigProperties props) {
this.props = props;
@Override
public PooledObject<FTPClient> makeObject() throws Exception {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(props.getHost(), props.getPort());
ftpClient.login(props.getUsername(), props.getPassword());
log.info("连接FTP服务器返回码{}", ftpClient.getReplyCode());
ftpClient.setBufferSize(props.getBufferSize());
// ftpClient.setControlEncoding(props.getEncoding());
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
return new DefaultPooledObject<>(ftpClient);
} catch (Exception e) {
log.error("建立FTP连接失败", e);
if (ftpClient.isAvailable()) {
ftpClient.disconnect();
ftpClient = null;
throw new Exception("建立FTP连接失败", e);
@Override
public void destroyObject(PooledObject<FTPClient> p) throws Exception {
FTPClient ftpClient = getObject(p);
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect();
@Override
public boolean validateObject(PooledObject<FTPClient> p) {
FTPClient ftpClient = getObject(p);
if (ftpClient == null || !ftpClient.isConnected()) {
return false;
try {
ftpClient.changeWorkingDirectory("/");
return true;
} catch (Exception e) {
log.error("验证FTP连接失败::{}", ExceptionUtils.getStackTrace(e));
return false;
@Override
public void activateObject(PooledObject<FTPClient> p) throws Exception {
@Override
public void passivateObject(PooledObject<FTPClient> p) throws Exception {
private FTPClient getObject(PooledObject<FTPClient> p) {
if (p == null || p.getObject() == null) {
return null;
return p.getObject();
2.4 把配置文件中 连接FTP服务器的配置也贴出来吧
#ftp config
ftp.enabled=true
#ftp 服务器地址
ftp.host=127.0.0.1
#ftp 端口
ftp.port=21
ftp.username=admin
ftp.password=admin
关于获取远程文件(例如FTP等)系统上音频文件到这里就结束了,感谢大家的阅读,希望对各位有所帮助。
另外最近在系统的学习大数据Hadoop生态圈相关知识,一些练习已经上传至github,并且会持续更新,有兴趣的小伙伴们可以互相交流下:
hadoop相关练习 github地址:https://github.com/Higmin/bigdata.git
官网下载:https://sourceforge.net/projects/jacob-project/
2、把下载解压之后里面的“jacob-1.19-x64.dll”文件复制到jdk安装的bin目录中(切记:.dll文件根据自己电脑位数选择不同的文件)。
3、通过...
这次采用jacob实现,相比百度AI需要联网,本项目定位内网环境实现。核心代码,这样就可以输入文字,生成音频文件保存到本地目录中,然后下载音频文件就只需要读取文件就可以。jacob.jar:放入到项目中并配置下pox和Idea 的dependencies下。输入文字(支持中英文),点击转换生成***.wav文件,点击下载到本地就可。本次采用版本jacob-1.19,我们需要下载jacob.jar和dll。通过上面的几个文件代码,就可以实现文章前面web页面的效果了。jacob.dll:配置到jdk环境中。
1.Model、ModelMap和ModelAndView的使用详解
Spring-MVC在请求处理方法可出现和返回的参数类型中,最重要就是Model和ModelAndView了,对于MVC框架,控制器Controller执行业务逻辑,用于产生模型数据Model,而视图View用于渲染模型数据。
SpringMVC在调用方法前会创建一个隐含的数据模型,作为模型数据(Mode...
文章目录前言HttpServletResponseHttpMessageConverter配置实现ResponseEntityResource实现结论
项目开发中,会经常遇到需要下载的功能,即后台返回图片、音视频这类的文件流,记录下多种实现方式。
HttpServletResponse
HttpMessageConverter
ResponseEntity
Resource
HttpServletResponse
图像下载的最基本方法是直接针对响应对象实现:
@RequestMapping(val
记:5月18号下午
刚帮客户解锁登陆ip后,客户求助导出excel无响应,于是博主赶忙尝试登陆系统边尝试导出边思考,是否最近一次更新系统不小心更错了,仔细一想,上次更新内容不多不至于影响导出这一块代码。
于是我打开日志,找到了ClientAbortException: java.net.SocketException: Connection reset by pee...
response.reset(); File excelFile = new File(filePath); // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("application/octet-stream"); // 2.设置文件头:处理文件名...
public void upload(MultipartFile excelFile) {
String fileName = excelFile.getOriginalFilename();
BufferedInputStream bi=null;
BufferedOutputStream bo = null;
File file =