需求
提供一个接口,前端通过按钮下载文件,根据不同的id下载对应的文件
编写接口相关代码
controller
/**
* 下载文件
*
* @param signId
*/@GetMapping("/downloadFile")@ApiOperationSupport(order =5)@ApiOperation(value ="下载文档", notes ="传入signId")publicvoiddownloadFile(@ApiParam(value ="签署id", required =true)@RequestParamLong signId,HttpServletResponse response)throwsException{
signDocumentService.downloadFile(signId,response);}
mapper
/**
* 根据singId查询Attach
*
* @param singId
* @return SignDocument
*/List<Map<String,String>>selectAttachs(@Param("singId")Long singId);
mapper.xml
<select id="selectAttachs" resultType="map">
select
ba.link filePath,ba.original_name fileName
from dmyz_sign_document dsd
left join blade_attach ba on ba.id=dsd.attach_id
where sign_id =#{singId} and dsd.is_deleted =0</select>
service
/**
* 根据id查询附件并下载
*
* @param signId
* @param response
* @throws Exception
*/voiddownloadFile(Long signId,HttpServletResponse response)throwsIOException;
serviceImpl
这里我要从oss上下载,所以我先从oss下载到项目本地了,不然File无法识别远程文件,只能识别本地文件,这块逻辑自行修改,代码参考即可
/**
* 根据id查询附件并下载
*
* @param signId
* @param response
* @throws Exception
*/@OverridepublicvoiddownloadFile(Long signId,HttpServletResponse response)throwsIOException{String path =null;String download =null;ServletOutputStream out=null;FileInputStream fis=null;try{// 根据signId查询签署文档List<Map<String,String>> maps = signDocumentMapper.selectAttachs(signId);// 如果不为空if(!maps.isEmpty()){for(Map<String,String> map : maps){String link = map.get("filePath");String uuid = UUID.randomUUID().toString().replace("-","");// 文件名称 uuid随机生成String fileName =uuid+PDF;// 把oss文件下载到项目本地
path =SignDocumentServiceImpl.class.getClass().getResource("/").getPath()+FileUtil.getNameWithoutExtension(link)+ PDF;// 把获取到的oss文件链接下载到本地
download =download(link, path);File file =newFile(download);
response.setCharacterEncoding("utf-8");
response.setContentType("application/file");
response.setHeader("Content-Disposition","attachment;FileName="+ fileName);
out = response.getOutputStream();int len =0;byte[] buffer =newbyte[1024];
fis =newFileInputStream(file);while((len = fis.read(buffer))>0){
out.write(buffer,0, len);
out.flush();}
response.flushBuffer();}}}catch(Exception e){
log.error("下载单个pdf文件失败,原因:{}", e);}finally{
out.close();
fis.close();}}
访问接口测试
浏览器输入
localhost:8080/downloadFile?signId=1001
本地选择保存目录
点击保存 就看到在指定的位置上有我们的文件了
可以正常打开查看
版权归原作者 小花皮猪 所有, 如有侵权,请联系我们删除。