com.sc.utils.utils.FileItem Maven / Gradle / Ivy
The newest version!
package com.sc.utils.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileItem {
private String fileName;
private String mimeType;
private byte[] content;
private File file;
public FileItem(File file) {
this.file = file;
}
public FileItem(String filePath) {
this(new File(filePath));
}
public FileItem(String fileName, byte[] content) {
this.fileName = fileName;
this.content = content;
}
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 = getMimeType(getContent());
}
return this.mimeType;
}
private String getMimeType(byte[] bytes) {
String suffix = getFileSuffix(bytes);
String mimeType;
if ("JPG".equals(suffix)) {
mimeType = "image/jpeg";
} else if ("GIF".equals(suffix)) {
mimeType = "image/gif";
} else if ("PNG".equals(suffix)) {
mimeType = "image/png";
} else if ("BMP".equals(suffix)) {
mimeType = "image/bmp";
} else {
mimeType = "application/octet-stream";
}
return mimeType;
}
private String getFileSuffix(byte[] bytes) {
if (bytes == null || bytes.length < 10) {
return null;
}
if (bytes[0] == 'G' && bytes[1] == 'I' && bytes[2] == 'F') {
return "GIF";
} else if (bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G') {
return "PNG";
} else if (bytes[6] == 'J' && bytes[7] == 'F' && bytes[8] == 'I' && bytes[9] == 'F') {
return "JPG";
} else if (bytes[0] == 'B' && bytes[1] == 'M') {
return "BMP";
} else {
return null;
}
}
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;
}
}