赞
踩
最近开发有个需求是,实现浏览器预览pdf文件,数据库存储的pdf文件url地址,通过url地址下载pdf文件,并返回流,最终实现pdf文件预览,需求不难,以下提供我的解决思路。
点击按钮打开pdf
打开实现打开pdf方法
- openpdf (url) {
- // window.open(url,'_blank');
-
- const sendurl = "/file/download";
- download(sendurl,{fileUrl:url}).then((res) => {
- const binaryData=[];
- binaryData.push(res)
- window.open(window.URL.createObjectURL(new Blob(binaryData,{'type':'application/pdf'})))
- let objectUrl = window.URL.createObjectURL(new Blob([res]));
- const elink = document.createElement('a');
-
- })
- },
发起请求的封装,responseType很重要,须设置为blob
- export function download(url,param,data) {
- return request({
- url: url,
- method: "post",
- params: param,
- data,
- responseType: 'blob',//将文件流转成blob对象
- noErrorMsg: false
- });
- }
- @Value("${web.upload-path}")
- private String rootPath;
-
- @RequestMapping(value = "/download", method = RequestMethod.POST)
- public HttpServletResponse download(String fileUrl, HttpServletResponse response) throws IOException {
- // path是指欲下载的文件的路径。
- File file = new File(rootPath+"/"+fileUrl);
- // 取得文件名。
- String filename = file.getName();
- // 取得文件的后缀名。
- String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
- // 以流的形式下载文件。
- InputStream fis = new BufferedInputStream(new FileInputStream(rootPath+"/"+fileUrl));
- byte[] buffer = new byte[fis.available()];
- fis.read(buffer);
- fis.close();
- // 清空response
- response.setCharacterEncoding("utf-8");
- // response.setHeader("Content-disposition", "attachment;filename="+ filename + ".pdf");
- // 设置response的Header
- response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
- response.addHeader("Content-Length", "" + file.length());
- OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
- // response.setContentType("application/octet-stream");
- toClient.write(buffer);
- toClient.flush();
- toClient.close();
-
-
- return response;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。