java spring 下载_SpringBoot环境下java实现文件的下载

该代码段展示了如何在Spring MVC应用中实现文件下载功能。通过`@GetMapping`注解处理请求,替换路径中的冒号为文件分隔符,获取上传目录下的文件,并使用`HttpServletResponse`进行文件流的输出,确保文件能够正确发送到客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.cst.icode.controller;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.cst.util.file.Files;

import com.cst.util.file.Files.CstDir;

@RestController

@RequestMapping("/file")

public class TestController {

@GetMapping("/froalar/get/{path}")

public Object getFroalarFile(@PathVariable String path,HttpServletResponse re) {

path=path.replace(":", File.separator);

// 平台的下载文件根路径

File uploadRoot = Files.getDir(CstDir.upload);//=后面是要获得下载的文件的路径

File downloadDir = new File(uploadRoot, File.separator+path);

return downloadFile(downloadDir,re);

}

private OutputStream downloadFile(File file,HttpServletResponse re) {

if (file.exists()) {

byte[] buffer = new byte[1024];

FileInputStream fis = null;

BufferedInputStream bis = null;

try {

fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);

int i = bis.read(buffer);

OutputStream os = re.getOutputStream();

while (i != -1) {

os.write(buffer,0,i);

i = bis.read(buffer);

}

return os;

} catch (Exception e) {

e.printStackTrace();

} 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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值