| | |
| | | package com.hx.util; |
| | | |
| | | import com.hx.exception.TipsException; |
| | | import org.apache.commons.fileupload.FileItem; |
| | | import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
| | | import org.apache.commons.io.IOUtils; |
| | |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | import org.springframework.web.multipart.commons.CommonsMultipartFile; |
| | | import sun.misc.BASE64Decoder; |
| | | import sun.misc.BASE64Encoder; |
| | | |
| | | import java.io.*; |
| | | import java.net.URL; |
| | |
| | | /** |
| | | * 获取文件base64字符串 |
| | | * @param urlPath 文件路径 |
| | | * @return |
| | | * @throws IOException |
| | | * @return 返回base64编码 |
| | | */ |
| | | public static String getFileBaseStrByUrl(String urlPath) throws IOException { |
| | | InputStream is = getUrlFile(urlPath); |
| | |
| | | } |
| | | } |
| | | |
| | | public static String encodeBase64File(File file) throws Exception { |
| | | FileInputStream fileInputStream = new FileInputStream(file); |
| | | byte[] bytes = new byte[fileInputStream.available()]; |
| | | // 读取到 byte 里面 |
| | | fileInputStream.read(bytes); |
| | | fileInputStream.close(); |
| | | BASE64Encoder base64Encoder = new BASE64Encoder(); |
| | | // 得到文件 之后转成beye 然后使用base64转码 |
| | | // 转码 |
| | | String encode = base64Encoder.encode(bytes); |
| | | return encode; |
| | | } |
| | | |
| | | public static String encodeBase64File(MultipartFile multipartFile) throws Exception { |
| | | if (multipartFile == null) { |
| | | throw new TipsException("未检查到上传的文件!"); |
| | | } |
| | | String imageBaseStr = null; |
| | | try { |
| | | String contentType = multipartFile.getContentType(); |
| | | byte[] imageBytes = multipartFile.getBytes(); |
| | | BASE64Encoder base64Encoder = new BASE64Encoder(); |
| | | // imageBaseStr = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes); |
| | | imageBaseStr = base64Encoder.encode(imageBytes); |
| | | imageBaseStr = imageBaseStr.replaceAll("[\\s*\t\n\r]", ""); |
| | | } catch (IOException e) { |
| | | throw new TipsException("文件转换base64异常"); |
| | | } |
| | | //返回生成的编码 |
| | | return imageBaseStr; |
| | | } |
| | | } |