How to convert Base64 to MultipartFile (correction of popular implementation class BASE64DecodedMultipartFile)

Posted by BoxingKing on Sun, 23 Jan 2022 08:00:23 +0100

[copyright notice] for non-commercial purposes, indicate the source and can be reproduced freely
Blog address: https://blog.csdn.net/ShuSheng0007/article/details/118230374
From: shusheng007

summary

Two days ago, I met a need to convert Base64 to MultipartFile, so I searched on the Internet. It was the same article moved from a foreign website, and then there was no explanation or change. There were many areas that needed improvement. It was a fierce copy. Alas, there is still a big gap between domestic IT and foreign countries. Chinese people still need to work hard. First, their attitude should be changed.

In view of this, I'm going to sort out this piece briefly and strive to make our future generations know both what it is and why it is! Back wave, come on, wolf!

Online examples

It's really a fierce copy. You copy me and I copy you. If you search BASE64DecodedMultipartFile on the search engine, you can see that the Chinese copy the same article. You see, the following usage is also a fierce copy. No matter why it is written, is it right. Someone also asked: what should 256 be added to the byte [] array after base64 decoding? See what puzzles the next generation of IT workers in our motherland?

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]);

When I first saw the BASE64DecodedMultipartFile class and its usage on the Internet, I felt puzzled, mainly because it was written based on the base64 string with DataURI. If you get pure Base64 data, I believe you are confused.

The use method is also debatable. After decoding from base64 to byte [], it is really inexplicable to check whether it contains negative values. You decode the data from base64. The values must be within 0 ~ 64. Where is the negative number?

BASE64Decoder is clearly marked as not recommended by Java officials, and may be deleted or modified in the future, and no one cares.

After thinking about it, I'd better write an article. It's also a little effort to correct this topic. I hope someone can see it and correct the poison of base64 to MultipartFile on the Chinese Internet.

Implementation class

Since MultipartFile is an interface, and the Java class library does not provide a suitable implementation class to convert Base64 to MultipartFile, we need to implement this interface ourselves. There are several points to pay attention to in the implementation process.

First, determine whether the base64 data you want to process carries a DataURI, as shown below

data:image/jpeg;base64,/9j/4AA...

If we take it, we can get the file's contentType, file extension, etc.

  1. The getOriginalFilename() method is better to bring the file extension. For example, if your is an image, bring it jpg .png or something.
  2. The getContentType() method returns its content type, such as image/png

Here is an implementation class I improved

/**
 * Created by ShuSheng007
 * <p>
 * author     : ShuShneg007
 * date       : 2021/6/25 19:09
 * description:
 */
public class Base64ToMultipartFile implements MultipartFile {
    private final byte[] fileContent;

    private final String extension;
    private final String contentType;


    /**
     * @param base64
     * @param dataUri     The format is similar to: data:image/png;base64
     */
    public Base64ToMultipartFile(String base64, String dataUri) {
        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        this.extension = dataUri.split(";")[0].split("/")[1];
        this.contentType = dataUri.split(";")[0].split(":")[1];
    }

    public Base64ToMultipartFile(String base64, String extension, String contentType) {
        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        this.extension = extension;
        this.contentType = contentType;
    }

    @Override
    public String getName() {
        return "param_" + System.currentTimeMillis();
    }

    @Override
    public String getOriginalFilename() {
        return "file_" + System.currentTimeMillis() + "." + extension;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return fileContent == null || fileContent.length == 0;
    }

    @Override
    public long getSize() {
        return fileContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return fileContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(fileContent);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(fileContent);
        }
    }

}

use

The only thing to note is that if you want to convert base64 without DataURI, you have two options,

The first method is to create one according to the actual situation, as in the example code.
The second way is to use another constructor

Base64ToMultipartFile(String base64, String extension, String contentType)

Example code:

 public Boolean uploadFile(String base64) {
     final String[] base64Array = base64.split(",");
     String dataUir, data;
     if (base64Array.length > 1) {
         dataUir = base64Array[0];
         data = base64Array[1];
     } else {
         //Build according to the specific file you represent
         dataUir = "data:image/jpg;base64";
         data = base64Array[0];
     }
     MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
     ...
     return true;
 }

summary

The above is the whole content. I hope it can be helpful to those in need. If you dig more, you will be better than others.

The article on Base64 algorithm is recommended Let you thoroughly understand the base64 algorithm (what is Base64, what problems Base64 solves, and what is = at the end of Base64 string)

It's time to praise and support again. I think the significance of this article is different from others. Let's support more. Let's reverse those wrong plagiarism articles on the Internet together.

GitHub source address: Base64ToMultipartFile.java

Topics: Java base64