base64编码后的图片转为MultipartFile 2


使用MultipartFile 就可以接收前端传输过来的图片,但是在某些情况下,前端传输的是一段经过Base64编码过后的图片字符串,那么就需要再转换成图片存储,在进行保存数据库(图片路径)

 
 

我们都知道,网页上的图片资源如果采用http形式的url的话都会额外发送一次请求,网页发送的http请求次数越多,会造成页面加载速度越慢。而采用Base64格式的编码,将图片转化为字符串后,图片文件会随着html元素一并加载,这样就可以减少http请求的次数,对于网页优化是一种比较好的手段。

原文地址:https://www.cnblogs.com/ziyoublog/p/9389050.html。

百度两个个工具类

public class Base64DecodeMultipartFile implements MultipartFile {

    private final byte[] imgContent; private final String header; public Base64DecodeMultipartFile(byte[] imgContent, String header) { this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() { return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() { return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @Override public boolean isEmpty() { return imgContent == null || imgContent.length == 0; } @Override public long getSize() { return imgContent.length; } @Override public byte[] getBytes() throws IOException { return imgContent; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { new FileOutputStream(dest).write(imgContent); } } /*
     * base64转multipartFile
     * */
    public static MultipartFile base64Convert(String base64) { String[] baseStrs = base64.split(","); //base64编码后的图片有头信息所以要分离出来 [0]data:image/png;base64, 图片内容为索引[1]
BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; try { b = decoder.decodeBuffer(baseStrs[1]); //取索引为1的元素进行处理 } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new Base64DecodeMultipartFile(b, baseStrs[0]);//处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
}

返回MultipartFile对象

处理过后的照片是没有后缀的,需要手动拼接上去.

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM