调用方法:showPdf
传递参数: 网络路径
实现原理
1.根据路径把PDF存储在本地项目
2.根据存储路径获得PDF字节流
======================================
前端部分处理
前端需要先根据返回值中的statusCode= 200
确定返回成功状态,然后调用fs.writeFile进行文件读取,获取到的返回值是乱码为正常现象
========================================
后端代码处理
public static byte[] showPdf(HttpServletResponse response, String path) {
FileInputStream in;
OutputStream out;
byte[] b = new byte[10*1024];
try {
String generate = UUIDUtil.getuuid();
String dir = downLoadByUrl(path,generate+".PDF");
in = new FileInputStream(new File(dir));
out = response.getOutputStream();
while ((in.read(b)) != -1) {
out.write(b);
out.flush();
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**
* 从网络Url中下载文件
* @param urlStr
* @param fileName
* @throws IOException
*/
public static String downLoadByUrl(String urlStr,String fileName) throws IOException{
//获取项目路径,把文件存入项目根路径
String relativelyPath=System.getProperty("user.dir");
//根据项目路径创建文件夹
String separator = File.separator;
String savePath = relativelyPath+separator+"PDF";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
//文件保存位置
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
return file.getPath();
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}