下載遠端圖片並返回給前端
阿新 • • 發佈:2021-10-20
1.測試介面
@GetMapping("test") private void test(HttpServletRequest request, HttpServletResponse response){ String fileName = "94e497d0ad37b6087de56e068fa034c6.xlsx"; String filePath = "https://www.baidu.com/94e497d0ad37b6087de56e068fa034c6.xlsx"; FileUtils.download(response, filePath, fileName);// 下載操作 }
2.實現:FileUtils.java
public static boolean download(HttpServletResponse response, String filePath, String fileName) { URL url = null; URLConnection con = null; InputStream is = null; OutputStream os = null; response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("content-disposition", "attachment;filename=" + fileName); try { url = new URL(filePath); con = url.openConnection(); con.setConnectTimeout(5 * 1000); is = con.getInputStream(); // 開始讀取 int len; byte[] bs = new byte[1024]; os = response.getOutputStream(); while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } return true; } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { os.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; }