java spring 下载文件_springboot下载文件(使用流)

该代码段展示了如何在Java中实现文件下载功能。FileServiceImpl.java通过URLDecoder解码文件路径,设置响应类型为'application/octet-stream',并使用HttpServletResponse输出文件流。FileController.java则处理GET请求,调用服务层方法完成文件下载。
部署运行你感兴趣的模型镜像

1.FileServiceImpl.java

/**

* 下载文件

*

* @param address

* @param response

* @throws IOException

*/

@Override

public void downloadFile(String address, HttpServletResponse response) throws IOException {

if (address.contains("%")) {

try {

address = URLDecoder.decode(address, "UTF-8");

} catch (UnsupportedEncodingException e) {

throw new CyException("文件路径有误");

}

}

ServletOutputStream out = null;

FileInputStream in = null;

try {

in = new FileInputStream(new File(address));

String[] dir = address.split("/");

String fileName = dir[dir.length - 1];

// 设置响应类型为html,编码为utf-8,处理相应页面文本显示的乱码

response.setContentType("application/octet-stream");

// 设置文件头:最后一个参数是设置下载文件名

response.setHeader("Content-disposition", "attachment;filename=" + fileName);

out = response.getOutputStream();

// 读取文件流

int len = 0;

byte[] buffer = new byte[1024 * 10];

while ((len = in.read(buffer)) != -1) {

out.write(buffer, 0, len);

}

out.flush();

} catch (FileNotFoundException e) {

throw new CyException("文件路径有误");

} finally {

response.flushBuffer();

try {

out.close();

in.close();

} catch (NullPointerException e) {

throw new CyException("responseFileStream stream close() error:NullPointerException" + e.toString());

} catch (Exception e) {

throw new CyException("responseFileStream stream close() error:" + e.toString());

}

}

}

2.FileController.java

@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)

@ResponseBody

@Validated

public void downloadFile(@NotBlank @RequestParam(value = "address") String address, HttpServletResponse response)

throws IOException {

fileService.downloadFile(address, response);

}

您可能感兴趣的与本文相关的镜像

Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值