ANDRU-PC\Andru
2023-09-18 691dee7a71996cd99fdfe30bd61b2da95cc88ecd
提交 | 用户 | age
c1a9ee 1 package com.hx.util;
F 2
0a4d0a 3 import com.hx.exception.TipsException;
c1a9ee 4 import org.apache.commons.fileupload.FileItem;
F 5 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
6 import org.apache.commons.io.IOUtils;
7 import org.springframework.http.MediaType;
8 import org.springframework.web.multipart.MultipartFile;
9 import org.springframework.web.multipart.commons.CommonsMultipartFile;
248c35 10 import sun.misc.BASE64Decoder;
0a4d0a 11 import sun.misc.BASE64Encoder;
c1a9ee 12
F 13 import java.io.*;
14 import java.net.URL;
15 import java.net.URLConnection;
16 import java.util.Base64;
17
18 /**
19  * 文件转换工具类
20  * @USER: fhx
21  * @DATE: 2022/3/2
22  **/
23 public class FileConvertTool {
24
25     private static final int  BUFFER_SIZE = 2 * 1024;
26
27
28     /** 获取网络路径文件流 */
29     public static InputStream getUrlFile(String urlPath) throws IOException {
30         if(StringUtils.isEmpty(urlPath)){
31             return null;
32         }
33         // 构造URL
34         URL url = new URL(urlPath);
35         // 打开连接
36         URLConnection con = url.openConnection();
37         //设置请求超时为5s
38         con.setConnectTimeout(5*1000);
39         // 输入流
40         InputStream is = con.getInputStream();
41         return is;
42     }
43
44     /**
45      * 获取文件base64字符串
46      * @param urlPath  文件路径
47      * @return
48      * @throws IOException
49      */
50     public static String getFileBaseStrByUrl(String urlPath) throws IOException {
51         InputStream is = getUrlFile(urlPath);
52         byte[] bytes = IOUtils.toByteArray(is);
53         String encoded = Base64.getEncoder().encodeToString(bytes);
54         return encoded;
55     }
56
57     // inputStream转outputStream
58     public static ByteArrayOutputStream parse(final InputStream in) throws Exception {
59         final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
60         int ch;
61         while ((ch = in.read()) != -1) {
62             swapStream.write(ch);
63         }
64         return swapStream;
65     }
66
67     // outputStream转inputStream
68     public static ByteArrayInputStream parse(final OutputStream out) throws Exception {
69         ByteArrayOutputStream baos = new ByteArrayOutputStream();
70         baos = (ByteArrayOutputStream) out;
71         final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
72         return swapStream;
73     }
74
75     // inputStream转String
76     public static String parse_String(final InputStream in) throws Exception {
77         final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
78         int ch;
79         while ((ch = in.read()) != -1) {
80             swapStream.write(ch);
81         }
82         return swapStream.toString();
83     }
84
85     // OutputStream 转String
86     public static String parse_String(final OutputStream out) throws Exception {
87         ByteArrayOutputStream baos = new ByteArrayOutputStream();
88         baos = (ByteArrayOutputStream) out;
89         final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
90         return swapStream.toString();
91     }
92
93     // String转inputStream
94     public static ByteArrayInputStream parse_inputStream(final String in) throws Exception {
95         final ByteArrayInputStream input = new ByteArrayInputStream(in.getBytes());
96         return input;
97     }
98
99     // String 转outputStream
100     public static ByteArrayOutputStream parse_outputStream(final String in) throws Exception {
101         return parse(parse_inputStream(in));
102     }
103
104     /**
105      * 根据byte数组,生成文件
106      */
107     public static File getFile(byte[] bfile, String filePath,String fileName) {
108         BufferedOutputStream bos = null;
109         FileOutputStream fos = null;
110         File file = null;
111         try {
112             File dir = new File(filePath);
113             if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
114                 dir.mkdirs();
115             }
116             file = new File(filePath+"\\"+fileName);
117             fos = new FileOutputStream(file);
118             bos = new BufferedOutputStream(fos);
119             bos.write(bfile);
120         } catch (Exception e) {
121             e.printStackTrace();
122         } finally {
123             if (bos != null) {
124                 try {
125                     bos.close();
126                 } catch (IOException e1) {
127                     e1.printStackTrace();
128                 }
129             }
130             if (fos != null) {
131                 try {
132                     fos.close();
133                 } catch (IOException e1) {
134                     e1.printStackTrace();
135                 }
136             }
137         }
138         return file;
139     }
140
141     /**
142      * 根据byte数组,生成文件
143      */
144     public static File getFile(InputStream in, String filePath, String fileName) {
145         if(in == null){
146             return null;
147         }
148         BufferedOutputStream bos = null;
149         FileOutputStream fos = null;
150         File file = null;
151         try {
152             File dir = new File(filePath);
153             //判断文件目录是否存在
154             if(!dir.exists()){
155                 dir.mkdirs();
156             }
157             file = new File(filePath+"/"+fileName);
158             fos = new FileOutputStream(file);
159             byte[] b = new byte[BUFFER_SIZE];
160 //            while ((in.read(b)) != -1) {
161 //                fos.write(b); // 写入数据
162 //            }
163             int len;
164             while ((len = in.read(b)) != -1){
165                 fos.write(b, 0, len);
166             }
167             in.close();
168         } catch (Exception e) {
169             e.printStackTrace();
170         } finally {
171             if (bos != null) {
172                 try {
173                     bos.close();
174                 } catch (IOException e1) {
175                     e1.printStackTrace();
176                 }
177             }
178             if (fos != null) {
179                 try {
180                     fos.close();
181                 } catch (IOException e1) {
182                     e1.printStackTrace();
183                 }
184             }
185         }
186         return file;
187     }
188
189     /**
190      * 获得指定文件的byte数组
191      */
192     private static byte[] getBytes(String filePath){
193         byte[] buffer = null;
194         try {
195             File file = new File(filePath);
196             FileInputStream fis = new FileInputStream(file);
197             ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
198             byte[] b = new byte[1000];
199             int n;
200             while ((n = fis.read(b)) != -1) {
201                 bos.write(b, 0, n);
202             }
203             fis.close();
204             bos.close();
205             buffer = bos.toByteArray();
206         } catch (FileNotFoundException e) {
207             e.printStackTrace();
208         } catch (IOException e) {
209             e.printStackTrace();
210         }
211         return buffer;
212     }
213
214     public static MultipartFile getMultipartFile(File file) {
215         FileItem item = new DiskFileItemFactory().createItem("file"
216                 , MediaType.MULTIPART_FORM_DATA_VALUE
217                 , true
218                 , file.getName());
219         try (InputStream input = new FileInputStream(file);
220              OutputStream os = item.getOutputStream()) {
221             // 流转移
222             IOUtils.copy(input, os);
223         } catch (Exception e) {
224             throw new IllegalArgumentException("Invalid file: " + e, e);
225         }
226
227         return new CommonsMultipartFile(item);
228     }
229
230     /**
231      *  根据路径删除指定的目录或文件,无论存在与否
232      *@param sPath  要删除的目录或文件
233      *@return 删除成功返回 true,否则返回 false。
234      */
235     public static boolean deleteFolder(String sPath) {
236         File file = new File(sPath);
237         // 判断目录或文件是否存在
238         if (!file.exists()) {
239             // 不存在返回 true
240             return true;
241         } else {
242             // 判断是否为文件
243             if (file.isFile()) {  // 为文件时调用删除文件方法
244                 return deleteFile(sPath);
245             } else {  // 为目录时调用删除目录方法
246                 return deleteDirectory(sPath);
247             }
248         }
249     }
250
251     /**
252      * 删除单个文件
253      * @param   sPath    被删除文件的文件名
254      * @return 单个文件删除成功返回true,否则返回false
255      */
256     public static boolean deleteFile(String sPath) {
257         File  file = new File(sPath);
258         // 路径为文件且不为空则进行删除
259         if (file.isFile() && file.exists()) {
260             file.delete();
261             return true;
262         }
263         return false;
264     }
265
266     /**
267      * 删除目录(文件夹)以及目录下的文件
268      * @param   sPath 被删除目录的文件路径
269      * @return  目录删除成功返回true,否则返回false
270      */
271     public static boolean deleteDirectory(String sPath) {
272         //如果sPath不以文件分隔符结尾,自动添加文件分隔符
273         if (!sPath.endsWith(File.separator)) {
274             sPath = sPath + File.separator;
275         }
276         File dirFile = new File(sPath);
277         //如果dir对应的文件不存在,或者不是一个目录,则退出
278         if (!dirFile.exists() || !dirFile.isDirectory()) {
279             return false;
280         }
281         boolean flag = true;
282         //删除文件夹下的所有文件(包括子目录)
283         File[] files = dirFile.listFiles();
284         for (int i = 0; i < files.length; i++) {
285             //删除子文件
286             if (files[i].isFile()) {
287                 flag = deleteFile(files[i].getAbsolutePath());
288                 if (!flag) break;
289             } //删除子目录
290             else {
291                 flag = deleteDirectory(files[i].getAbsolutePath());
292                 if (!flag) break;
293             }
294         }
295         if (!flag) return false;
296         //删除当前目录
297         if (dirFile.delete()) {
298             return true;
299         } else {
300             return false;
301         }
302     }
248c35 303
0a4d0a 304     public static String encodeBase64File(File file) throws Exception {
F 305         FileInputStream fileInputStream = new FileInputStream(file);
306         byte[] bytes = new byte[fileInputStream.available()];
307         // 读取到 byte 里面
308         fileInputStream.read(bytes);
309         fileInputStream.close();
310         BASE64Encoder base64Encoder = new BASE64Encoder();
311         // 得到文件 之后转成beye 然后使用base64转码
312         // 转码
313         String encode = base64Encoder.encode(bytes);
314          return encode;
315     }
248c35 316
0a4d0a 317     public static String encodeBase64File(MultipartFile multipartFile) throws Exception {
F 318         if (multipartFile == null) {
319             throw new TipsException("未检查到上传的文件!");
320         }
321         String imageBaseStr = null;
322         try {
323             String contentType = multipartFile.getContentType();
324             byte[] imageBytes = multipartFile.getBytes();
325             BASE64Encoder base64Encoder = new BASE64Encoder();
326 //            imageBaseStr = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
327             imageBaseStr = base64Encoder.encode(imageBytes);
328             imageBaseStr = imageBaseStr.replaceAll("[\\s*\t\n\r]", "");
329         } catch (IOException e) {
330             throw new TipsException("文件转换base64异常");
331         }
332         //返回生成的编码
333         return imageBaseStr;
334     }
c1a9ee 335 }