1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Java图片上传Base64 类型上传 后台转换工具类

Java图片上传Base64 类型上传 后台转换工具类

时间:2020-05-17 13:53:22

相关推荐

Java图片上传Base64 类型上传 后台转换工具类

java图片上传Base64 类型上传 后台转换工具类

import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import org.springframework.web.multipart.MultipartFile;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;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];}@Overridepublic String getName() {// TODO - implementation depends on your requirementsreturn System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];}@Overridepublic String getOriginalFilename() {// TODO - implementation depends on your requirementsreturn System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];}@Overridepublic String getContentType() {// TODO - implementation depends on your requirementsreturn header.split(":")[1];}@Overridepublic boolean isEmpty() {return imgContent == null || imgContent.length == 0;}@Overridepublic long getSize() {return imgContent.length;}@Overridepublic byte[] getBytes() throws IOException {return imgContent;}@Overridepublic InputStream getInputStream() throws IOException {return new ByteArrayInputStream(imgContent);}@Overridepublic void transferTo(File dest) throws IOException, IllegalStateException {new FileOutputStream(dest).write(imgContent);}/***将图片Base64 码转成上传流*/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字符串转byte[]public static byte[] base64String2Byte(String base64Str) throws IOException{BASE64Decoder decoder = new BASE64Decoder();return decoder.decodeBuffer(base64Str);}////byte[]转base64public static String byte2Base64String(byte[] b){BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(b);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。