日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

MultipartFile與base64互轉

作者:dexi.Chi 程序猿 更新時間: 2022-07-16 編程語言

MultipartFile轉base64

/**
 * 將MultipartFile 圖片文件編碼為base64
 * @param file
 * @return
 * @throws Exception
 */
public static String generateBase64(MultipartFile file){
	if (file == null || file.isEmpty()) {
		throw new RuntimeException("圖片不能為空!");
	}
	String fileName = file.getOriginalFilename();
	String fileType = fileName.substring(fileName.lastIndexOf("."));
	String contentType = file.getContentType();
	byte[] imageBytes = null;
	String base64EncoderImg="";
	try {
		imageBytes = file.getBytes();
		BASE64Encoder base64Encoder =new BASE64Encoder();
		/**
		 * 1.Java使用BASE64Encoder 需要添加圖片頭("data:" + contentType + ";base64,"),
		 *   其中contentType是文件的內容格式。
		 * 2.Java中在使用BASE64Enconder().encode()會出現字符串換行問題,這是因為RFC 822中規定,
		 *   每72個字符中加一個換行符號,這樣會造成在使用base64字符串時出現問題,
		 *   所以我們在使用時要先用replaceAll("[\\s*\t\n\r]", "")解決換行的問題。
		 */
		base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
		base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return base64EncoderImg;
}

base64轉MultipartFile
思路: 先將base64轉成File,再將File轉成MultipartFile

base64轉File,涉及使用枚舉類

/**
 * base64文件類型,前綴
 * @author
 */
public enum Base64FileTypeEnum {
    // 文件類型
    BASE64_FILETYPE_DOC(".doc", "data:application/msword;base64"),
    BASE64_FILETYPE_DOCX(".docx", "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64"),
    BASE64_FILETYPE_XLS(".xls", "data:application/vnd.ms-excel;base64"),
    BASE64_FILETYPE_XLSX(".xlsx", "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64"),
    BASE64_FILETYPE_PDF(".pdf", "data:application/pdf;base64"),
    BASE64_FILETYPE_PPT(".ppt", "data:application/vnd.ms-powerpoint;base64"),
    BASE64_FILETYPE_PPTX(".pptx", "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64"),
    BASE64_FILETYPE_TXT(".txt", "data:text/plain;base64"),

    // 圖片類型
    BASE64_FILETYPE_PNG(".png", "data:image/png;base64"),
    BASE64_FILETYPE_JPG(".jpg", "data:image/jpeg;base64"),
    BASE64_FILETYPE_JPEG(".jpeg", "data:image/jpeg;base64"),
    BASE64_FILETYPE_GIF(".gif", "data:image/gif;base64"),
    BASE64_FILETYPE_SVG(".svg", "data:image/svg+xml;base64"),
    BASE64_FILETYPE_ICO(".ico", "data:image/x-icon;base64"),
    BASE64_FILETYPE_BMP(".bmp", "data:image/bmp;base64"),

//    // 二進制流
//    BASE64_FILETYPE_OCTET_STREAM("octet-stream", "data:application/octet-stream;base64,"),
    ;

   private Base64FileTypeEnum(String code, String value) {
        this.code = code;
        this.value = value;
    }

   private String code;
   private String value;

   public String getCode() {return code;}
   public String getValue() {return value;}

   public static String getFileType(String value) {
        Base64FileTypeEnum[] types = values();
        for (Base64FileTypeEnum x : types) {
            if (x.getValue().equals(value)) {
                return x.getCode();
            }
        }
        return null;
    }
}
//BASE64解碼成File文件
public File base64ToFile(String base64, String fileName) {
	File file = null;
	//創建文件目錄
	String filePath=this.getClass().getClassLoader().getResource("").getPath();
	File  dir=new File(filePath);
	if (!dir.exists() && !dir.isDirectory()) {
		dir.mkdirs();
	}
	BufferedOutputStream bos = null;
	FileOutputStream fos = null;
	try {
		//截取base64頭部,獲取文件類型
		String fileType = Base64FileTypeEnum.getFileType(base64.substring(0, base64.indexOf(",")));
		//去掉頭部,防止轉換文件后打開顯示文件損壞
		String s = base64.substring(base64.indexOf(",")+1);
		byte[] bytes = new BASE64Decoder().decodeBuffer(s);
		file=new File(filePath+"/"+fileName+fileType);
		fos = new FileOutputStream(file);
		bos = new BufferedOutputStream(fos);
		bos.write(bytes);
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (bos != null) {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (fos != null) {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	return file;
}

生成File后我們轉成MultipartFile

//File轉MultipartFile
public static MultipartFile getMultipartFile(File file) {
	FileItem item = new DiskFileItemFactory().createItem("file"
			, MediaType.MULTIPART_FORM_DATA_VALUE
			, true
			, file.getName());
	try (InputStream input = new FileInputStream(file);
		 OutputStream os = item.getOutputStream()) {
		// 流轉移
		IOUtils.copy(input, os);
	} catch (Exception e) {
		throw new IllegalArgumentException("Invalid file: " + e, e);
	}

	return new CommonsMultipartFile(item);
}

原文鏈接:https://blog.csdn.net/weixin_43949154/article/details/125783459

欄目分類
最近更新