Spring:如何下载文件? [英] Spring: how to download file?

查看:129
本文介绍了Spring:如何下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将zip存档从服务器保存到用户计算机。我有一个网页,显示有关此文件的一些信息,并有一个下载按钮。在我的控制器操作按钮上只需重定向主页,但我想从数据库中获取数据并将其保存到用户机器,路径由用户定义

I want to save zip archive from server to user computer. I have web page that shows some information about this file and has a download button. In my controller action on button simply redirect on homepage but I want to get data from database and save it to user machine with path is defined by user

问题是我不知道如何能够走这条道路。你能给我一个例子我怎么做?

The issue is that I don't know how I can get this path. Could you give me an example how I can do that?

推荐答案

在你的控制器方法中你可以添加这段代码来获取文件下载

In your controller method you can add this code to get file download

File file = new File("fileName");
FileInputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
ServletContext sc = request.getSession().getServletContext();
String mimetype = sc.getMimeType(file.getName());
response.reset();
response.setContentType(mimetype);
response.setContentLength(content.length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
org.springframework.util.FileCopyUtils.copy(content, response.getOutputStream());

这篇关于Spring:如何下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆