当前位置:   article > 正文

Base64与File之间的相互转化_base64 file length

base64 file length

问题:最近遇到一个上传文件的问题,前端使用了另一种传值,就是Base64字符串传给后台 ,一开始没有对其进行解码操作,存入数据库时就超长了,今天这里提供一种base64和file之间相互转化的工具类,以便日后参考

  1. /**
  2. *
  3. * @param path
  4. * @return String
  5. * @description 将文件转base64字符串
  6. * @date 2018年3月20日
  7. * @author changyl
  8. * File转成编码成BASE64
  9. */
  10. public static String fileToBase64(String path) {
  11. String base64 = null;
  12. InputStream in = null;
  13. try {
  14. File file = new File(path);
  15. in = new FileInputStream(file);
  16. byte[] bytes=new byte[(int)file.length()];
  17. in.read(bytes);
  18. base64 = Base64.getEncoder().encodeToString(bytes);
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. } finally {
  22. if (in != null) {
  23. try {
  24. in.close();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }
  30. return base64;
  31. }
  1. //BASE64解码成File文件
  2. public static void base64ToFile(String destPath,String base64, String fileName) {
  3. File file = null;
  4. //创建文件目录
  5. String filePath=destPath;
  6. File dir=new File(filePath);
  7. if (!dir.exists() && !dir.isDirectory()) {
  8. dir.mkdirs();
  9. }
  10. BufferedOutputStream bos = null;
  11. java.io.FileOutputStream fos = null;
  12. try {
  13. byte[] bytes = Base64.getDecoder().decode(base64);
  14. file=new File(filePath+"/"+fileName);
  15. fos = new java.io.FileOutputStream(file);
  16. bos = new BufferedOutputStream(fos);
  17. bos.write(bytes);
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. } finally {
  21. if (bos != null) {
  22. try {
  23. bos.close();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. if (fos != null) {
  29. try {
  30. fos.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }
  36. }

☛需要注意:标红的base64在这里需要去掉

baseStr = baseStr.replace("data:image/jpeg;base64,", "");//base64解密部分乱码问题(“+” 号,在urlecode编码中会被解码成空格)



本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号