Base64转MultipartFile实现

前记:上传图片文件,我要求的方式是前端使用最简单的multipart/form-data,后台使用的是MultipartFile[]的方式接收,但是前端小哥用MUI一直发送失败,改用base64的方式发送。后端接收base64字符串后,装换成MultipartFile的方式,然后用Thumbnails对图片进行修改。


1.直接上代码吧!

解析Base64

package com.itkim.util;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.IOException;

/**
 * @description: 传入图片的base64
 * @author: KimJun
 * @date: 18/11/13 00:25
 */
public class base64ToMultipart {
    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;
        }
    }
  
    //测试
    public static void main(String[] args) {
        MultipartFile multipartFiles[] = new MultipartFile[2];
        multipartFiles[0] = base64ToMultipart.base64ToMultipart("");
        System.out.println(multipartFiles[0].getSize());
        
    }
}
package com.itkim.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @description: TODO
 * @author: KimJun
 * @date: 18/11/12 23:37
 */

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() {
        // 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() {
        // TODO - implementation depends on your requirements
        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);
    }I
}

2.图片的实体类(补上实体类)

package com.itkim.entity;

/**
 * @description: TODO
 * @author: KimJun
 * @date: 18/11/12 22:20
 */
public class Pic {
    //图片的id 第几张。
    private String picNum;

    //图片的Base64编码
    private String picString;

    public String getPicNum() {
        return picNum;
    }

    public String getPicString() {
        return picString;
    }

    @Override
    public String toString() {
        return "Pic{" +
                "picNum='" + picNum + '\'' +
                ", picString='" + picString + '\'' +
                '}';
    }
}

3.前端测试代码(需要jQuery)




    
    Title
    



请输入图片的Base64码 1--
请输入图片的Base64码 2--

4.Controller接收

@RequestMapping(value = "additem", method = RequestMethod.POST)  
@ResponseBody
public Msg multipartFileUpload(@RequestBody List pictureFiles) throws IOException {
    System.out.println(pictureFiles.toString());
    System.out.println(pictureFiles.size());
    //如果图片的长度、大于8则抛异常
    if (pictureFiles.size() > 8) {
        return Msg.fail("上传失败,图片的张数大于8");
    } else {
        //新建一个数组接收保存
        MultipartFile[] pictureFile = new MultipartFile[pictureFiles.size()];
        for (int i = 0; i < pictureFiles.size(); i++) {
            String ImgBase = pictureFiles.get(i).getPicString();
            System.out.println(ImgBase);
            if (!ImgBase.equals(null)) {
                pictureFile[i] = base64ToMultipart.base64ToMultipart(ImgBase);
            } else {
                break;
            }
        }
    }

你可能感兴趣的:(Base64转MultipartFile实现)