spring boot 解決圖片 ,txt點選路徑等直接開啟而無法下載的問題
阿新 • • 發佈:2018-12-13
前臺(ftl)
<a href="/file/down?url='html路徑'&name='檔名'" download>下載</a>
後臺(controller)
@GetMapping("/file/down") public void Down(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String name = req.getParameter("name");//獲取要下載的檔名 //第一步:設定響應型別 name = URLEncoder.encode(name, "UTF-8"); resp.setHeader("Content-Disposition", "attachment;filename="+name); resp.setContentType("application/force-download");//應用程式強制下載 //第二讀取檔案 String url = req.getParameter("url"); OutputStream out = resp.getOutputStream(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpResp = httpclient.execute(httpGet); try { HttpEntity httpEntity = httpResp.getEntity(); resp.setContentLength((int)httpEntity.getContentLength()); IOUtils.copy(httpEntity.getContent(), out); } catch (Exception ex) { httpclient.close(); } out.flush(); out.close(); }