java如何将base64上传的文件转换为MultipartFile对象呢?

书欣 Java经验 发布时间:2022-08-28 12:34:04 阅读数:1482 1
下文笔者讲述base64格式上传文件的处理方法分享,如下所示
我们都知道上传文件都是file对象
但是如果我们使用base64格式上传文件
需转换为Multipartfile对象
然后进行处理
例:
package com.java265.upload.config;

import org.springframework.web.multipart.MultipartFile; 
import java.io.*;
/**
 * 自定义的MultipartFile的实现类
 * 主要用于base64上传文件
 * 以下方法都可以根据实际项目自行实现
 */
public class BASE64DecodedMultipartFile implements MultipartFile {
 
    private final byte[] imgContent;
    private final String header;
 
    public BASE64DecodedMultipartFile(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,如下:
package com.java265.upload.config;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.IOException;
  
@Slf4j
public class Base64Util {
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStr = base64.split(",");
 
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStr[1]);
 
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
 
            return new BASE64DecodedMultipartFile(b, baseStr[0]);
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }
}

//测试文件上传的Controller 
/**
 * 上传图片
 */
@Slf4j
@RestController
public class CommentImageUploadController {
 
    @Value("${fileupload.path}")
    private String fileuploadPath;
 
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    public ApiResponse uploadImage(String image, HttpServletResponse response) {
 
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
// image格式: "data:image/png;base64," + "图片的base64字符串"
            MultipartFile multipartFile = Base64Util.base64ToMultipart(image);
 
            String originalFilename = multipartFile.getOriginalFilename();
 
            // 文件扩展名
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".")).trim();
 
            list<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
            if (!extList.contains(ext)) {
                return ApiResponse.error("图片格式非法!");
            }
 
            String randomFilename = System.currentTimeMillis() + NumberUtil.getRandomString(6) + ext;
            //将文件写入服务器
            String fileLocalPath = fileuploadPath + "commentImage/" + randomFilename;
            File localFile = new File(fileLocalPath);
            multipartFile.transferTo(localFile);
 
            //写入服务器成功后组装返回的数据格式
            Map<String, Object> fileMap = new HashMap<>();
            //文件存放路径
            fileMap.put("filePath", "testImage/" + randomFilename);
            return ApiResponse.success(fileMap);
        } catch (Exception e) {
            log.error("上传图片失败:", e);
        }
        return ApiResponse.error();
    }
}

前端传输示例
image:'data:image/png;base64,'+'图片的base64字符串'
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202208/16616613034273.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者