前端
axios({
method: "post",
url: "/checkUrl",
data: {"requestUrl": queryParameters.url},
headers: {
"Content-Type": 'application/x-www-form-urlencoded',
"Authorization": '......'
},
responseType: 'blob' //重要的是设置responseType
}).then((res)=>{
console.log(res);
})
后端
public static void inputStream2File(String fileURL, HttpServletResponse response){
try {
String filename = URLEncoder.encode("文件名.pdf", "UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);//浏览器上提示下载时默认的文件名
URL url = new URL(fileURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 得到输入流
InputStream inputStream = conn.getInputStream();
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
// 关闭输入流和输出流
inputStream.close();
out.close();
out.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
参考文档: