1.后端输出字节流
public void getFileStream(Long ossFileId, HttpServletResponse response) {
InputStream inputStream = null;
try {
OssFile vo = fileService.getById(ossFileId);
String fileUrl = minioTemplate.getObjectUrl(vo.getBucketName(), vo.getFilename());
//如果是pdf直接输出流预览,如果是excel转换成pdf预览,如果是其他文件,输出“改文件格式不支持预览!”
if (vo.getFileSuffix().equals("xls") || vo.getFileSuffix().equals("xlsx")) {
InputStream inputStream2 = new FileInputStream(AsposeUtils.excel2pdfBySuffix(fileUrl, vo.getFileSuffix()));
response.getOutputStream().write(readInputStream(inputStream2));
inputStream2.close();
} else if (vo.getFileSuffix().equalsIgnoreCase("pdf")) {
inputStream = new URL(fileUrl).openStream();
response.getOutputStream().write(readInputStream(inputStream));
} else if (vo.getContentType().toLowerCase().indexOf("image") > -1) {
InputStream inputStream2 = new FileInputStream(AsposeUtils.image2pdfBySuffix(fileUrl, vo.getFileSuffix()));
response.getOutputStream().write(readInputStream(inputStream2));
inputStream2.close();
} else if (vo.getFileSuffix().equalsIgnoreCase("doc") || vo.getFileSuffix().equalsIgnoreCase("docx")) {
InputStream inputStream2 = new FileInputStream(AsposeUtils.word2pdfBySuffix(fileUrl, vo.getFileSuffix()));
response.getOutputStream().write(readInputStream(inputStream2));
inputStream2.close();
}else if (vo.getFileSuffix().equalsIgnoreCase("dwg")) {
InputStream inputStream2 = new FileInputStream(AsposeUtils.dwg2pdfBySuffix(fileUrl, vo.getFileSuffix()));
response.getOutputStream().write(readInputStream(inputStream2));
inputStream2.close();
} else {
response.getOutputStream().write(readInputStream(AsposeUtils.getPreTitle()));
}
inputStream.close();
} catch (Exception e) {
try {
response.getOutputStream().write(readInputStream(AsposeUtils.getPreTitle()));
if (inputStream != null) {
inputStream.close();
}
} catch (Exception ee) {
}
}
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[inputStream.available()];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
2.前端get请求方式
/**
* 根据文件id查询文件流以pdf方式预览
* @param id
* @returns {*}
*/
export function getFileStream(id) {
return `${api.darwing}` + '/file/pre/' + id
}
//调用:
window.open('/pdf/web/viewer.html?file=' + encodeURIComponent(getFileStream(record.id)) + '#page=1');
3.前端携带token请求方式
/**
* 根据文件id查询文件流以pdf方式预览
* @param id
* @returns {*}
*/
export function getFileStream(id) {
return axios({
url: `${api.darwing}` + '/file/pre/' + id,
method: 'get',
responseType: 'blob'
})
}
// 后台返回流的形式
getFileStream(record.id).then((res)=>{
let blob = new Blob([res.data],{type:"application/octet-stream"});
let url = window.URL.createObjectURL(blob)
this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(url) + '#page=1'
})