springboot 文件单个下载实现

单个文件本地服务器下载实现

service层接口定义代码
public interface IDownloadFileService {
	// 单个文件下载
	public void downloadFile(String fileName);
}
service层接口实现类代码
@Service
public class DownloadFileServiceImpl implements IDownloadFileService {

	@Value("${file.path}")
	private String FILE_ROOT_PATH;

	@Override
	public void downloadFile(String fileName) {

		// 获取response对象
		HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		// 获取服务器本地的文件位置
		File file = new File(FILE_ROOT_PATH + fileName);

		if (file.exists()) {
			BufferedInputStream bufferedInputStream = null;
			BufferedOutputStream bufferedOutputStream = null;
			try {
				resp.setContentType("application/x-msdownload");
				resp.setHeader("Content-Dispostion",
						"attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
				FileInputStream inputStream = new FileInputStream(file);
				bufferedInputStream = new BufferedInputStream(inputStream); //缓冲流加速读

				OutputStream outputStream = resp.getOutputStream();
				bufferedOutputStream = new BufferedOutputStream(outputStream);  //缓冲流加速写
				// byte b[]=new byte[1024];
				int n;
				while ((n = bufferedInputStream.read()) != -1) {
					// outputStream.write(b,0,n);
					bufferedOutputStream.write(n);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					bufferedOutputStream.close();
					bufferedInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			throw new RuntimeException("文件在本地服务器不存在");
		}
	}
}
controller层实现类代码
@RestController
@RequestMapping("/file")
public class DownLoadFileController {

	@Autowired
	private DownloadFileServiceImpl downloadFileServiceImpl;

	@GetMapping("/downloadsinglefile")
	public void downloadSingleFile(@RequestParam(value = "filename") String fileName)       		    
	{
		downloadFileServiceImpl.downloadFile(fileName);
	}
}	
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>下载测试</title>
</head>
<body>
  <a href="/file/downloadsinglefile?filename=xxxname" download="xxxname" >下载1 </a>
  <a href="/file/downloadsinglefile?filename=8.19.jpg" download="8.19.jpg" >下载2 </a>
  <a href="/file/downloadsinglefile?filename=idea文档.pdf" download="idea文档.pdf" >下载3 </a>
</body>
</html>
配置文件application.properties
server.port=8083
//本地服务器上存放需要下载的文件位置  eg: /root/git/xxxdir 我这里项目在window上就在本地测试了
file.path=C:\\Users\\wanlf\\Desktop\\\u7167\u7247\\
实现效果图

在这里插入图片描述
以上就是单个文件下载案例

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值