后端文件存储(开发日志01-后端以文件流的形式供前端下载)
导读:需求: 本地有一个生成sql脚本的文档,预留了很多类似 {{xxx}} 需要替换的地方 。...
需求:
本地有一个生成sql脚本的文档 ,预留了很多类似 {{xxx}} 需要替换的地方 。
该需求是 需要前端传入响应的值 替换掉 模板中预留的需要被替换的位置
最后 通过Post请求返回给前端一个供其下载一个.sql脚本文件
实现步骤
1 、首先 ,考虑到打包后的路径问题
想到了SpringBoot工程下的Resource目录下
所以 我们需要的模板文件跟提供给前端下载的文件就放在 Resource 目录下的static文件夹里
//于是我就写了一个方法用于提取该路径 //用到了Spring ApplicationHome类的方法 public String getSavePath() { ApplicationHome applicationHome = new ApplicationHome(this.getClass()); return applicationHome.getDir().getParentFile() .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\"; }2 、文件复制替换
这里我试过用FileReader和FileWriter方法
但是由于 这两个方法是不可以设定文件encode编码的(或者是可以 我不会 = =!)
所以,因为需要替换的地方不多 ,我就想到了一部分用字符串拼接 ,一部分用BufferedWriter写
由于业务需要 写了两个其他方法 生成随机一位字符串 private String MkRandomNum() { Random random = new Random(); String randomNum = ""; for (int i = 0; i < 9; i++) { randomNum += random.nextInt(10); } return randomNum; } 日期格式的转换 private String toFormatDate(String modifyTime) { Date format2 = null; try { format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(modifyTime); } catch (ParseException e) { throw new RuntimeException(e); } String shortDate = new SimpleDateFormat("yyyyMMddHHmmss").format(format2); return shortDate; }读取原模板文件为字符串并设置字符编码
public String readToString(String fileName) { String encoding = "UTF-8"; File file = new File(fileName); Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch (UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } }3 、使用HttpServletResponse返回给前端
@Override public void export(HttpServletResponse response) throws IOException { String realPath = getSavePath()+"demo2.sql"; String fileName = ("model.sql"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); FileInputStream fis = new FileInputStream(realPath); //5 、创建缓冲区 int len = 0; byte[] bytes = new byte[1024]; //6 、创建输出流 ServletOutputStream sot = response.getOutputStream(); //7 、写出文件 while ((len = fis.read(bytes)) != -1) { sot.write(bytes, 0, len); sot.flush(); } //8 、关闭流 sot.close(); fis.close(); }4 、部分结果展示
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!