当前位置:   article > 正文

SpringBoot生成docx文件并返回其Base64编码_springboot word 转base64

springboot word 转base64

直接上源码,

 

  1. @ResponseBody
  2. @RequestMapping(value = "/getDocx", method = RequestMethod.GET)
  3. public String getDocumentBase64(@RequestBody JSONObject jsonParam, HttpServletResponse res){
  4. String fileName = "default.docx";
  5. String base64String = "";
  6. InputStream in = null;
  7. byte[] fileByte = null;
  8. try{
  9. JSONObject massageJson = jsonParam.getJSONObject("massage");
  10. // 生成乱码名
  11. String documentTreesJson = jsonParam.getJSONObject("data").toJSONString();
  12. fileName = massageJson.getString("userName") + "__" + massageJson.getString("fileSuffix")
  13. + "__" + RandomUtil.getRandomString(32) + ".docx";
  14. // 生成docx 到fileName
  15. DocumentUtil.GenerateDocument(documentTreesJson, fileName);
  16. in = new FileInputStream(fileName); //通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的路径名 name 指定。
  17. int size = in.available(); // 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。
  18. fileByte = new byte[size];
  19. in.read(fileByte); //从此输入流中将最多 size 个字节的数据读入一个 imageByte字节 数组中。
  20. in.close(); //关闭此文件输入流并释放与此流有关的所有系统资源。
  21. }catch (Docx4JException e){
  22. System.out.println("生成docx文件失败,Json:" + jsonParam.toJSONString());
  23. }catch (Exception e){
  24. System.out.println("创建输出流失败,Json:" + jsonParam.toJSONString());
  25. JSONObject massageJson = jsonParam.getJSONObject("massage");
  26. String documentTreesJson = jsonParam.getString("data");
  27. System.out.println(massageJson.toJSONString());
  28. System.out.println("data: " + documentTreesJson);
  29. } finally{
  30. BASE64Encoder encoder = new BASE64Encoder();
  31. base64String = encoder.encode(fileByte);// 对字节数组转换成Base64字符串
  32. if(!IOUtil.delFile(new File(fileName))){
  33. System.err.println("文件未成功删除");
  34. }
  35. }
  36. // System.out.println(base64String);
  37. return base64String;
  38. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/853384
推荐阅读
相关标签
  

闽ICP备14008679号