提交 | 用户 | age
|
826b66
|
1 |
package com.hx.util; |
C |
2 |
|
|
3 |
import org.apache.commons.fileupload.FileItem; |
|
4 |
import org.apache.commons.fileupload.FileItemFactory; |
|
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; |
|
10 |
|
|
11 |
import java.io.*; |
|
12 |
|
|
13 |
public class MultipartFileUtil { |
|
14 |
|
|
15 |
|
|
16 |
/**文件转化 |
|
17 |
* File to MultipartFile |
|
18 |
* @param file |
|
19 |
* @return |
|
20 |
*/ |
|
21 |
public static MultipartFile getMultipartFile(File file) { |
|
22 |
FileItem item = new DiskFileItemFactory().createItem("file" |
|
23 |
, MediaType.MULTIPART_FORM_DATA_VALUE |
|
24 |
, true |
|
25 |
, file.getName()); |
|
26 |
try (InputStream input = new FileInputStream(file); |
|
27 |
OutputStream os = item.getOutputStream()) { |
|
28 |
// 流转移 |
|
29 |
IOUtils.copy(input, os); |
|
30 |
} catch (Exception e) { |
|
31 |
throw new IllegalArgumentException("Invalid file: " + e, e); |
|
32 |
} |
|
33 |
return new CommonsMultipartFile(item); |
|
34 |
} |
|
35 |
|
|
36 |
|
|
37 |
/**文件转化 |
|
38 |
* File to MultipartFile |
|
39 |
* @param file 文件 |
|
40 |
* @param fileName 带后缀的文件名 |
|
41 |
* @return |
|
42 |
*/ |
|
43 |
public static MultipartFile getMultipartFile(File file,String fileName) { |
|
44 |
FileItem item = new DiskFileItemFactory().createItem("file" |
|
45 |
, MediaType.MULTIPART_FORM_DATA_VALUE |
|
46 |
, true |
|
47 |
, StringUtils.isEmpty(fileName)?file.getName():fileName); |
|
48 |
try (InputStream input = new FileInputStream(file); |
|
49 |
OutputStream os = item.getOutputStream()) { |
|
50 |
// 流转移 |
|
51 |
IOUtils.copy(input, os); |
|
52 |
} catch (Exception e) { |
|
53 |
throw new IllegalArgumentException("Invalid file: " + e, e); |
|
54 |
} |
|
55 |
return new CommonsMultipartFile(item); |
|
56 |
} |
|
57 |
|
|
58 |
} |