本地文件下載(須要文件的絕對路徑)spring
@Slf4j @Component public class CommonDownLoadUtil { /** * @param response 客戶端響應 * @throws IOException io異常 */ public void downLoad(HttpServletResponse response, String downloadUrl) throws Throwable { if (Objects.isNull(downloadUrl)) { // 若是接收參數爲空則拋出異常,由全局異常處理類去處理。 throw new NullPointerException("下載地址爲空"); } // 讀文件 File file = new File(downloadUrl); if (!file.exists()) { log.error("下載文件的地址不存在:{}", file.getPath()); // 若是不存在則拋出異常,由全局異常處理類去處理。 throw new HttpMediaTypeNotAcceptableException("文件不存在"); } // 獲取用戶名 String fileName = file.getName(); // 重置response response.reset(); // ContentType,即告訴客戶端所發送的數據屬於什麼類型 response.setContentType("application/octet-stream; charset=UTF-8"); // 得到文件的長度 response.setHeader("Content-Length", String.valueOf(file.length())); // 設置編碼格式 response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8")); // 發送給客戶端的數據 OutputStream outputStream = response.getOutputStream(); byte[] buff = new byte[1024]; BufferedInputStream bis = null; // 讀取文件 bis = new BufferedInputStream(new FileInputStream(new File(downloadUrl))); int i = bis.read(buff); // 只要能讀到,則一直讀取 while (i != -1) { // 將文件寫出 outputStream.write(buff, 0, buff.length); // 刷出 outputStream.flush(); i = bis.read(buff); } } }