Springboot實現文件下載功能

使用springboot實現文件下載

本地文件下載(須要文件的絕對路徑)spring

步驟一封裝文件下載api工具類:
@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);
        }
    }
}

備註:

  • 本文將工具類加了@Component交給spring管理了,固然,也能夠將此方法使用靜態方法封裝。
  • 本文的全局異常處理,能夠選擇try->catch,也可使用全局異常處理類去處理(全局異常具體看上文)。
  • 將工具類封裝以後,則可使用了,這裏代碼的調用,本文就再也不敘述了。
相關文章
相關標籤/搜索