当前位置: 代码迷 >> 综合 >> Springboot 下载文件
  详细解决方案

Springboot 下载文件

热度:59   发布时间:2024-02-07 12:46:41.0
public class FileUtil {/**** 文件下载* @param filename 需要下载文件的绝对路径* @param res* @throws IOException*/public static void download(String filename, HttpServletResponse res) throws IOException {InputStream inputStream = null;OutputStream os = null;try{File file = new File(filename);String name = file.getName();inputStream = new FileInputStream(file);ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len =0;while((len=inputStream.read(buffer))!=-1){outStream.write(buffer,0,len);}inputStream.close();byte[] data = outStream.toByteArray();res.reset();res.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));res.setContentType("application/octet-stream");os = res.getOutputStream();os.write(data);os.flush();os.close();}catch (Exception e){e.printStackTrace();throw new CommonException("导出元数据失败");}finally {if(inputStream!=null){inputStream.close();}if(os!=null){os.close();}}}
}