需求背景:
文件存在华为云上,想实现页面’点击下载‘拿到这条数据id,去后台查这条数据的华为云文件地址,下载文件,效果如下。。
弹出下载框
实战:
step one: 拿前台传过来的id去库里查这条数据文件的华为云地址
//1、获取华为云地址
String fileUrl = "";
try{
fileUrl = letterManageService.letterDownload(letterId);
}catch(BusinessException e){
logger.info("获取华为云地址失败。。失败原因:"+e.getErrorMsg());
e.printStackTrace();
throw BusinessException.build(e.getErrorCode()).message(e.getErrorMsg());
}
logger.info("权益确认函华为云地址: "+fileUrl);
tip:
养成好习惯:多打日志,多抛异常
step two: 根据网络地址获取输入流
//网络url - >输入流
java.net.URL url = new java.net.URL(fileUrl);
java.net.URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
step three: 设置response响应头
response.setHeader("content-type", "application/pdf");
response.setContentType("application/octet-stream");
response.setHead