背景:由于项目需求,需要将接口返回的pdf文件下载地址在页面预览出来,并将对应的文件流存储到mongodb里,但又不想下载文件,所以有了以下的方法。
- 如何在前端预览pdf文件?
这个大家可以自己搜一下,有使用iframe、pdf.js、embad、object、pdfObject等,我使用的iframe,没啥,就是因为简单,一行代码就行了。
//把下载地址放置到iframe标签的src属性中,就能预览pdf了
<iframe src="https://test.pdf" width="100%" height="100%"></iframe>
- 后端通过下载地址,将文件内容转成btye[]
/**
* 通过文件下载地址,读出字节流
* @param urlPath
* @return
*/
public byte[] getFileByteByUrl(String urlPath){
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
InputStream inputStream = new URL(urlPath).openStream();
byte[] buffer = new byte[1024*4];
int n = 0;
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (output != null) {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}