package eeting.upload;import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;/**
* Title: eMarketing Project
* Description: eMarketing Project
* Copyright: Copyright (c) 2001
* Company: Sydec
* @author Gerry Shall
* @version 1.0
*/public class UploadBean {
private String rootPath = "C:/UploadTemp";
private boolean canOverWrite = true;
private String logFileName = "C:/UploadTemp/upload.txt"; //set for test only. //The following variables can only be gotten.
private int maxFileSize = 1024 * 1024 * 10; //10M for default.
private int maxOneFileSize = this.maxFileSize;
private String pageContentType = "";
private byte dataBytes[];
private boolean hasLog = false; private Vector fileMess = new Vector(); public UploadBean(HttpServletRequest request, int maxFileSize) throws UploadException {
this(request, maxFileSize, -1); //If maxFileSize is set to "-1", it means it will neglect the size of one file when uploading.
} public UploadBean(HttpServletRequest request, int maxFileSize, int maxOneFileSize) throws UploadException {
ServletInputStream sin;
this.maxFileSize = maxFileSize * 1024; // K
try {
pageContentType = request.getContentType();
if(pageContentType != null && pageContentType.indexOf("multipart/form-data") != -1) {
sin = request.getInputStream();
int formDataLength = request.getContentLength();
dataBytes = new byte[formDataLength];
int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
String line;
String boundary = getBoundaryFromContentType(pageContentType);
boolean isFileName = false;
boolean isBoundary = false;
int fileStrIndex = 0;
int fileEndIndex = 0;
int lineCountAfterBoundary = 0;
String filename = "";
while (totalBytesRead < formDataLength) {
sizeCheck = totalBytesRead + sin.available();
if(sizeCheck > this.maxFileSize) {
sin.close();
throw new UploadException("The total size of the upload files is too large. The max file size is: " + this.maxFileSize + " bytes.");
}
if(fileStrIndex > 0 && maxOneFileSize > 0 && (sizeCheck - fileStrIndex) > Math.min(this.maxFileSize, maxOneFileSize)) {
sin.close();
throw new UploadException("The size of File: " + filename + " is too large. The max one file size is: " + maxOneFileSize + " bytes.");
}
bytesRead = sin.readLine(dataBytes, totalBytesRead, formDataLength);
line = new String(dataBytes, totalBytesRead, bytesRead);
isBoundary = hasBoundary(line, boundary);
if(isBoundary) {
lineCountAfterBoundary = 0;
if(isFileName == true) {
fileEndIndex = totalBytesRead - 2;
if(filename != null && filename.trim().length() > 0) {
if(fileEndIndex > fileStrIndex) {
fileMess.addElement(filename);
fileMess.addElement(new int[] {fileStrIndex, fileEndIndex});
}
else {
throw new UploadException("The file is invalid.");
}
}
}
isFileName = false;
}
else {
lineCountAfterBoundary++;
if(lineCountAfterBoundary == 1 && hasFileName(line)) {
filename = getFileName(line);
isFileName = true;
}
}
if(lineCountAfterBoundary == 4 && isFileName == true) {
fileStrIndex = totalBytesRead;
}
totalBytesRead += bytesRead;
}
//String content = new String(dataBytes);
}
else {
throw new UploadException("The page content type is not \"multipart/form-data\"!");
}
}
catch(IOException ioe) {
throw new UploadException(ioe.getMessage());
}
catch(UploadException ue) {
if(hasLog)
writeLog(ue.getMessage());
throw new UploadException(ue.getMessage());
}
}
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;/**
* Title: eMarketing Project
* Description: eMarketing Project
* Copyright: Copyright (c) 2001
* Company: Sydec
* @author Gerry Shall
* @version 1.0
*/public class UploadBean {
private String rootPath = "C:/UploadTemp";
private boolean canOverWrite = true;
private String logFileName = "C:/UploadTemp/upload.txt"; //set for test only. //The following variables can only be gotten.
private int maxFileSize = 1024 * 1024 * 10; //10M for default.
private int maxOneFileSize = this.maxFileSize;
private String pageContentType = "";
private byte dataBytes[];
private boolean hasLog = false; private Vector fileMess = new Vector(); public UploadBean(HttpServletRequest request, int maxFileSize) throws UploadException {
this(request, maxFileSize, -1); //If maxFileSize is set to "-1", it means it will neglect the size of one file when uploading.
} public UploadBean(HttpServletRequest request, int maxFileSize, int maxOneFileSize) throws UploadException {
ServletInputStream sin;
this.maxFileSize = maxFileSize * 1024; // K
try {
pageContentType = request.getContentType();
if(pageContentType != null && pageContentType.indexOf("multipart/form-data") != -1) {
sin = request.getInputStream();
int formDataLength = request.getContentLength();
dataBytes = new byte[formDataLength];
int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
String line;
String boundary = getBoundaryFromContentType(pageContentType);
boolean isFileName = false;
boolean isBoundary = false;
int fileStrIndex = 0;
int fileEndIndex = 0;
int lineCountAfterBoundary = 0;
String filename = "";
while (totalBytesRead < formDataLength) {
sizeCheck = totalBytesRead + sin.available();
if(sizeCheck > this.maxFileSize) {
sin.close();
throw new UploadException("The total size of the upload files is too large. The max file size is: " + this.maxFileSize + " bytes.");
}
if(fileStrIndex > 0 && maxOneFileSize > 0 && (sizeCheck - fileStrIndex) > Math.min(this.maxFileSize, maxOneFileSize)) {
sin.close();
throw new UploadException("The size of File: " + filename + " is too large. The max one file size is: " + maxOneFileSize + " bytes.");
}
bytesRead = sin.readLine(dataBytes, totalBytesRead, formDataLength);
line = new String(dataBytes, totalBytesRead, bytesRead);
isBoundary = hasBoundary(line, boundary);
if(isBoundary) {
lineCountAfterBoundary = 0;
if(isFileName == true) {
fileEndIndex = totalBytesRead - 2;
if(filename != null && filename.trim().length() > 0) {
if(fileEndIndex > fileStrIndex) {
fileMess.addElement(filename);
fileMess.addElement(new int[] {fileStrIndex, fileEndIndex});
}
else {
throw new UploadException("The file is invalid.");
}
}
}
isFileName = false;
}
else {
lineCountAfterBoundary++;
if(lineCountAfterBoundary == 1 && hasFileName(line)) {
filename = getFileName(line);
isFileName = true;
}
}
if(lineCountAfterBoundary == 4 && isFileName == true) {
fileStrIndex = totalBytesRead;
}
totalBytesRead += bytesRead;
}
//String content = new String(dataBytes);
}
else {
throw new UploadException("The page content type is not \"multipart/form-data\"!");
}
}
catch(IOException ioe) {
throw new UploadException(ioe.getMessage());
}
catch(UploadException ue) {
if(hasLog)
writeLog(ue.getMessage());
throw new UploadException(ue.getMessage());
}
}
private String getBoundaryFromContentType(String contentType) {
int index = contentType.lastIndexOf("=");
return contentType.substring(index+1, contentType.length());
}
//
private boolean hasBoundary(String line, String boundary) {
return line.indexOf(boundary) == -1 ? false : true;
}
//
private boolean hasFileName(String line) {
return line.indexOf("filename=\"") == -1 ? false : true;
}
//
private String getFileName(String line) {
int pos = line.indexOf("filename=\"");
if(pos == -1)
return null;
line = line.substring(pos + 10, line.lastIndexOf("\""));
pos = line.lastIndexOf('/');
if(pos != -1) {
line = line.substring(pos + 1, line.length());
}
else {
pos = line.lastIndexOf('\\');
if(pos != -1)
line = line.substring(pos + 1, line.length());
}
return line;
}
//
public static boolean deleteDirAndFiles(String path) {
boolean isSuccessful = true;
path = normalizePath(path);
File dir = new File(path);
try {
if(dir.exists()) {
String[] filelist = dir.list();
if(filelist != null && filelist.length != 0) {
File file;
for(int i = 0; i < filelist.length; i++) {
file = new File(path + filelist[i]);
file.delete();
}
}
dir.delete();
}
}
catch(Exception ioe) {
ioe.printStackTrace();
isSuccessful = false;
}
return isSuccessful;
}
public void upload(File dir) throws UploadException {
if(fileMess == null || fileMess.size() == 0)
return;
if(dir == null)
throw new UploadException("The given directory is null.");
try {
if(!dir.exists()) {
dir.mkdirs();
}
File file;
FileOutputStream fw;
String filename;
int index[];
int str = 0;
int end = 0;
for(int i = 0; i < fileMess.size(); i+=2) {
filename = (String)fileMess.elementAt(i);
index = (int[])fileMess.elementAt(i+1);
str = index[0];
end = index[1];
file = new File(dir, filename);
if(canOverWrite == true) {
if(file.exists() && (file.isDirectory() || !file.canWrite())) {
throw new UploadException("File can not be written.");
}
fw = new FileOutputStream(file);
fw.write(dataBytes, str, end - str);
fw.close();
}
else {
throw new UploadException("Can not over write the file, please set the variable \"canOverWrite\" value to \"True\".");
}
}
if(hasLog) {
writeLog(getUploadInformation());
}
}
catch(IOException ioe) {
throw new UploadException(ioe.getMessage());
}
catch(UploadException ue) {
if(hasLog)
writeLog(ue.getMessage());
throw new UploadException(ue.getMessage());
}
} public String uploadFileToPath(File dir) throws UploadException {
String filePath = null;
if(fileMess == null || fileMess.size() == 0)
return filePath;
if(dir == null)
throw new UploadException("The given directory is null.");
try {
if(!dir.exists()) {
dir.mkdirs();
}
File file;
FileOutputStream fw;
String filename;
int index[];
int str = 0;
int end = 0;
for(int i = 0; i < fileMess.size(); i+=2) {
filename = (String)fileMess.elementAt(i);
filePath = dir.getAbsolutePath() + "\\" + filename;
index = (int[])fileMess.elementAt(i+1);
str = index[0];
end = index[1];
file = new File(dir, filename);
if(canOverWrite == true) {
if(file.exists() && (file.isDirectory() || !file.canWrite())) {
throw new UploadException("File can not be written.");
}
fw = new FileOutputStream(file);
fw.write(dataBytes, str, end - str);
fw.close();
}
else {
throw new UploadException("Can not over write the file, please set the variable \"canOverWrite\" value to \"True\".");
}
}
if(hasLog) {
writeLog(getUploadInformation());
}
}
catch(IOException ioe) {
throw new UploadException(ioe.getMessage());
}
catch(UploadException ue) {
if(hasLog)
writeLog(ue.getMessage());
throw new UploadException(ue.getMessage());
}
return filePath;
}/*
//
if(fileMess == null || fileMess.size() == 0)
return;
try {
File dir = new File(rootPath);
if(!dir.exists()) {
dir.mkdirs();
}
File file;
FileOutputStream fw;
String filename;
int index[];
int str = 0;
int end = 0;
for(int i = 0; i < fileMess.size(); i+=2) {
filename = (String)fileMess.elementAt(i);
index = (int[])fileMess.elementAt(i+1);
str = index[0];
end = index[1];
file = new File(rootPath + filename);
if(canOverWrite == true) {
if(file.exists() && (file.isDirectory() || !file.canWrite())) {
throw new UploadException("File can not be written.");
}
fw = new FileOutputStream(file);
fw.write(dataBytes, str, end - str);
fw.close();
}
else {
throw new UploadException("Can not over write the file, please set the variable \"canOverWrite\" value to \"True\".");
}
}
if(hasLog) {
writeLog(getUploadInformation());
}
}
catch(IOException ioe) {
throw new UploadException(ioe.getMessage());
}
catch(UploadException ue) {
if(hasLog)
writeLog(ue.getMessage());
throw new UploadException(ue.getMessage());
}
}*/
public File getSaveDirectory() {
File f = new File(rootPath);
String prefix = "Version_";
String[] subDirs = f.list();
if(subDirs == null || subDirs.length == 0)
return new File(rootPath + File.separator + prefix + String.valueOf(1) + File.separator);
int max = 0;
int num = 0;
for(int i = 0; i < subDirs.length; i++) {
if(subDirs[i].startsWith(prefix)) {
try {
num = Integer.parseInt(subDirs[i].substring(prefix.length()));
if(num > max)
max = num;
}
catch(Exception e) {
continue;
}
}
}
File newDir = new File(f, prefix + String.valueOf(max + 1));
//return (newDir.mkdir()) ? newDir : null;
return newDir;
}
public File getSaveDirectory(String directory) {
File file = new File(directory);
file.mkdirs();
return file;
}
public static String normalizePath(String path) {
if(path == null || path.trim().length() == 0)
return "/";
path = path.replace('\\', '/');
if(path.indexOf("/") == -1)
return "/" + path + "/";
if(!path.trim().endsWith("/"))
path = path + "/";
if(path.indexOf(":") == -1 && !path.trim().startsWith("/"))
path = "/" + path;
return path;
}
public void setRootPath(String rootPath) {
rootPath = normalizePath(rootPath);
this.rootPath = rootPath;
}
public void setCanOverWrite(boolean canOverWrite) {
this.canOverWrite = canOverWrite;
}
public void setHasLog(boolean hasLog) {
this.hasLog = hasLog;
}
public void setLogFileName(String logFileName) {
this.logFileName = logFileName;
}
public int getMaxFileSize() {
return maxFileSize;
}
public int getMaxOneFileSize() {
return maxOneFileSize;
}
public String getRootPath() {
return rootPath;
}
public boolean canOverWrite() {
return canOverWrite;
}
public String getPageContentType() {
return pageContentType;
}
public byte[] getDataBytes() {
return dataBytes;
}
public String[] getUploadedFileName() {
if(fileMess == null || fileMess.size() == 0)
return null;
int size = fileMess.size()/2;
String[] filenames = new String[size];
for(int i = 0; i < size; i++) {
filenames[i] = (String)fileMess.elementAt(i*2);
}
return filenames;
}
public int[] getUploadedFileSize() {
if(fileMess == null || fileMess.size() == 0)
return null;
int size = fileMess.size()/2;
int[] filesize = new int[size];
int[] index;
for(int i = 0; i < size; i++) {
index = (int[])fileMess.elementAt(i*2+1);
filesize[i] = index[1] - index[0];
}
return filesize;
}
public String getUploadInformation() {
if(fileMess == null || fileMess.size() == 0)
return "No upload files information.";
StringBuffer sb = new StringBuffer("Upload Information\r\n\r\n");
sb.append("Max File Size: " + maxFileSize + " bytes\r\n");
sb.append("Page Content Type: " + pageContentType + "\r\n");
String[] filenames = this.getUploadedFileName();
int[] filesize = this.getUploadedFileSize();
int size = filenames.length;
if(size != filesize.length)
return "Information errors. \"Filename\"'s counts don't equal to the \"Filesize\"'s counts.";
for(int i = 0; i < size; i++) {
sb.append("\r\n**File " + i + "**\r\n");
sb.append("File Path: " + this.getRootPath() + "\r\n");
sb.append("File Name: " + filenames[i] + "\r\n");
sb.append("File Size: " + filesize[i] + " bytes\r\n");
}
return new String(sb);
}
private void writeLog(String content) throws UploadException {
try {
logFileName = this.rootPath + "upload.txt";
File file = new File(logFileName);
FileWriter fw = new FileWriter(file);
fw.write(content);
fw.close();
fw.close();
}
catch(IOException ioe) {
throw new UploadException(ioe.getMessage());
} }}