java将base64图片转为file上传到服务器

1,934 阅读1分钟

首先后台先创建工具类

public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
    this.imgContent = imgContent;
    this.header = header.split(";")[0];
}
 @Override
public String getName() {
    // TODO - implementation depends on your requirements
    return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
} 
@Override
public String getOriginalFilename() {
    // TODO - implementation depends on your requirements
    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);
} 
 public static MultipartFile base64ToMultipart(String base64) {
  try {
    String[] baseStrs = base64.split(",");
 
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] b = new byte[0];
    b = decoder.decodeBuffer(baseStrs[1]);
     for(int i = 0; i < b.length; ++i) {
        if (b[i] < 0) {
            b[i] += 256;
        }
    }
    return new BASE64DecodedMultipartFile(b, baseStrs[0]);
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }
}

后台接受base64数据


@RequestMapping(value = "uploadbase64", method = RequestMethod.POST)
 @ResponseBody
 public Map<String, Object> uploadbase64(HttpServletRequest request) throws IOException {
  String img=request.getParameter("img");
  MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(img);
  Oss o=osservice.selectById(1);
  UploadFile uf = new UploadFile();
  // 获取文件名
  String fileName = file.getOriginalFilename();
  // 获取文件后缀
  String prefix = fileName.substring(fileName.lastIndexOf("."));
  final File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
  file.transferTo(excelFile);
  oss.saveFileToOSS(excelFile, excelFile.getName());
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("code", 0);// 0表示成功,1失败
  map.put("msg", "上传成功");// 提示消息
  map.put("data", String.format("http://%s.%s/%s", o.getBucketName(), o.getEndpoint(), excelFile.getName()));
  return  map;
 }

本文使用 mdnice 排版