前端要預(yù)覽服務(wù)器PDF 可直接將要blob流返回給前端 即可用瀏覽器自帶pdf預(yù)覽功能打開(kāi),現(xiàn)有兩種方式
方式1 返回blob流給前端 代碼如下? ? ? ?
@PostMapping(value = "/preview")
@ResponseBody
public void showPdf(HttpServletResponse response) {
try {
File file = new File("filePath");
OutputStream out = null;
try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
) {
byte[] bs = new byte[1024];
int len;
response.reset(); // 非常重要
URL u = new URL("file:///" + "filePath");
String contentType = u.openConnection().getContentType();
response.setContentType(contentType);
response.setHeader("Content-Disposition", "inline;filename="
+ "preview.pdf");
out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
此時(shí) 前端解析可直接拿返回的文件流 例子如下
let blob = this.response;
const binaryData = [];
binaryData.push(blob);
const url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
window.open(url);
但有的時(shí)候 不想返回文件流 可把文件返回為base64 (注意 base64可能超長(zhǎng))此時(shí)代碼修改如下文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-720961.html
File file = new File("filePath");
OutputStream out = null;
try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
) {
int len;
URL u = new URL("file:///" + "filePath");
String contentType = u.openConnection().getContentType();
byte[] buffer = new byte[1024];
//每次讀取的字符串長(zhǎng)度,如果為-1,代表全部讀取完畢
//使用輸入流從buffer里把數(shù)據(jù)讀取出來(lái)
while ((len = br.read(buffer)) != -1) {
//用輸出流往buffer里寫入數(shù)據(jù),中間參數(shù)代表從哪個(gè)位置開(kāi)始讀,len代表讀取的長(zhǎng)度
outStream.write(buffer, 0, len);
}
// 對(duì)字節(jié)數(shù)組Base64編碼
Base64Encoder base64 = new Base64Encoder();
String base64Str = replaceEnter(base64.encode(outStream.toByteArray()));
}
} catch (Exception e) {
}
前端修改如下文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-720961.html
let base64 = resBase64.data.base64;
base64 = base64.replace(/[\n\r]/g, '')
const raw = window.atob(base64)
const rawLength = raw.length
const uInt8Array = new Uint8Array(rawLength)
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i)
}
const url = window.URL.createObjectURL(new Blob([uInt8Array], { type: resBase64.data.contentType }));
window.open(url);
到了這里,關(guān)于Java后端返回PDF預(yù)覽給前端的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!