FileItem.java
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.xiniunet.open.api.client;
import com.xiniunet.open.api.client.internal.util.ApiUtils;
import java.io.*;
/**
*/
public class FileItem {
private String fileName;
private String mimeType;
private byte[] content;
private File file;
/**
* 基于本地文件的构造器。
*
* @param file 本地文件
*/
public FileItem(File file) {
this.file = file;
}
/**
* 基于文件绝对路径的构造器。
*
* @param filePath 文件绝对路径
*/
public FileItem(String filePath) {
this(new File(filePath));
}
/**
* 基于文件名和字节流的构造器。
*
* @param fileName 文件名
* @param content 文件字节流
*/
public FileItem(String fileName, byte[] content) {
this.fileName = fileName;
this.content = content;
}
/**
* 基于文件名、字节流和媒体类型的构造器。
*
* @param fileName 文件名
* @param content 文件字节流
* @param mimeType 媒体类型
*/
public FileItem(String fileName, byte[] content, String mimeType) {
this(fileName, content);
this.mimeType = mimeType;
}
public String getFileName() {
if (this.fileName == null && this.file != null && this.file.exists()) {
this.fileName = file.getName();
}
return this.fileName;
}
public String getMimeType() throws IOException {
if (this.mimeType == null) {
this.mimeType = ApiUtils.getMimeType(getContent());
}
return this.mimeType;
}
public byte[] getContent() throws IOException {
if (this.content == null && this.file != null && this.file.exists()) {
InputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(this.file);
out = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1) {
out.write(ch);
}
this.content = out.toByteArray();
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
return this.content;
}
}