瀏覽器下載word.excel
阿新 • • 發佈:2018-11-16
/** * * @param filePath 路徑含檔案字尾//檔案完整路徑(包括檔名和副檔名) * @param name 下載後的名字 * @param response * @return * @throws IOException */ @Override public ApiResult getDownLoad(String filePath,String name,HttpServletResponse response) throws IOException { response.setCharacterEncoding("utf-8"); String url = URL + filePath; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); response.setContentType("application/octet-stream"); response.setHeader("name", name); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setDateHeader("Expires", 0); response.setHeader("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(name, "UTF-8") + "\""); CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpGet); HttpEntity entity = closeableHttpResponse.getEntity(); InputStream in = entity.getContent(); ServletOutputStream out = response.getOutputStream(); int b = 0; byte[] buffer = new byte[512]; while (b != -1) { b = in.read(buffer); //4.寫到輸出流(out)中 out.write(buffer, 0, b); } in.close(); out.close(); out.flush(); return new ApiResult().success(); }