通常的文件下载方法
@RequestMapping("/downLoadFile") public void downLoadLineStruImportTemplateFile(HttpServletResponse response) { byte buffer[] = new byte[1024]; int len = 0; try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/lineStruImportTemplate.xlsx"); OutputStream out = response.getOutputStream()) { response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setHeader( "Content-disposition", "attachment;filename=" + new String(("线路结构导入模板.xlsx").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } }
|
文件的下载:浏览器带进度显示
@RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) throws IOException { String filePath = "文件路径"; File file = new File(filePath); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setHeader( "Content-disposition", "attachment;filename=" + new String((file.getName()).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)); response.setContentLengthLong(file.length()); try (FileInputStream fileInputStream = new FileInputStream(file)) { OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); }
} catch (Exception e) { e.printStackTrace(); }
}
|
文件的预览(此时浏览器不会下载文件,而是会尽量渲染文件,比如音视频文件播放,图片、pdf会展示等
文件的预览和上面的代码基本一致,
但是去除设置头部信息的两行代码,
同时根据文件的类型设置不同的ContentType
@RequestMapping("/downLoadFile") public void downLoadLineStruImportTemplateFile(HttpServletResponse response) { byte buffer[] = new byte[1024]; int len = 0; try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/lineStruImportTemplate.xlsx"); OutputStream out = response.getOutputStream()) { response.setContentType(getMineType("lineStruImportTemplate.xlsx")); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); }
public static String getMineType(String name) { return TIKA.get().detect(name); }
public static String getMineType(byte[] data, String name) { return TIKA.get().detect(data, name); } }
|