SpringBoot如何通过一个url下载pdf到本地呢?
下文笔者讲述SpringBoot根据url下载pdf到本地的方法分享,如下所示
SpringBoot下载pdf到本地的实现思路
1.根据url,获取url对应的输入流 2.将获取的输入流copy到输出流中,进行相应的设置并返回例:SpringBoot根据url下载pdf的示例
@GetMapping(“/download”) public void download(@RequestParam(“url”) String urlStr, HttpServletResponse response) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置超时间为5秒 // conn.setConnectTimeout(5*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty(“User-Agent”, “Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)”); try(InputStream inputStream = conn.getInputStream(); OutputStream outputStream = response.getOutputStream()😉 { response.setContentType(“application/x-download”); response.addHeader(“Content-Disposition”, “attachment;filename=test.pdf”); // 将输入流拷贝到输出流中 IOUtils.copy(inputStream, outputStream); outputStream.flush(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。