MultipartFile 转 file 转base64字符串

背景:因业务需求需将MultipartFile 转 file 转base64传至第三方实现接入第三方文件上传

1.MultipartFile 转 file

    ①首先在Spring-mvc.xml中进行注入

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>

    ②用缓冲区实现转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法

public String uploadFAndD(@RequestParam(value = "file[]") MultipartFile mFiles, HttpServletRequest request,
File f = null;
try {
    f=File.createTempFile("tmp", null);
    mFiles.transferTo(f);
     f.deleteOnExit();     //使用完成删除文件   
} catch (HttpException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

2. file转base64字符串

    ①  java之文件转为base64字符
 FileInputStream inputFile = new FileInputStream(f);
 String base 64=null;
  byte[] buffer = new byte[(int) f.length()];
  inputFile.read(buffer);
  inputFile.close();
  base64=new BASE64Encoder().encode(buffer);

   ②注意:java中在使用BASE64Enconder().encode(buffer)会出现字符串换行问题,这是因为RFC 822中规定,每72个字符中加一个换行符号,这样会造成在使用base64字符串时出现问题,所以我们在使用时要先解决换行的问题

String encoded = base64.replaceAll("[\\s*\t\n\r]", "");

猜你喜欢

转载自blog.csdn.net/qq_41615095/article/details/80781933