文件下载
demo示例如下:
--前端代码,一个div,里放一个form 表单,填写请求路径 和请求方式
<div>
<form action="${ctx}/backup/backTables/downloadFile" method="post" enctype=multipart/form-data>
<button type="submit">下载备份文件</button>
</form>
</div>
-- Controller层写清楚映射
@Controller
@RequestMapping(value = "${adminPath}/backup/backTables")
public class BackUpController extends BaseController {
@RequestMapping(value = "downloadFile")
public void downloadFile(HttpServletResponse response) throws Exception {
backUpService.downloadFile(response);
}
}
--service 层实现下载功能
/**
* 下载文件到本地
*
* @throws UnsupportedEncodingException
*
* @throws IOException
*/
public void downloadFile(HttpServletResponse response) throws Exception {
Properties properties = properties();
String savePath = properties.getProperty("fileName");
// 下载服务器数据库备份文件到本地
FileInputStream in = null;
OutputStream out = null;
String filename = savePath.substring(savePath.lastIndexOf("/") + 1);
filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
try {
String downloadpath = savePath;
// 设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 读取要下载的文件,保存到文件输入流
in = new FileInputStream(downloadpath);
// 创建输出流
out = response.getOutputStream();
// 缓存区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区中
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭
in.close();
out.close();
}
// 删除服务器上的临时文件
File deleteFile = new File(savePath);
deleteFile.delete();
}
仅自己记录,每天进步一点点,生活变的好精彩;
posted on 2020-09-07 19:20 Spring-Boot-Cloud 阅读(168) 评论(0) 收藏 举报
浙公网安备 33010602011771号