在网上看到许多上传文件的例子,可是都是jsp程序,每碰到需要文件上传的地方就要复制这段上传代码并做相应修改,维护起来极不方便。为了增强代码的可重用性,我将这段通用的上传程序写成了JavaBean,请大家多提意见。
首先, 下载 commons-fileupload-1.0.zip 和 commons-beanutils-1.7.0.zip,
http://apache.freelamp.com/jakarta/commons/fileupload/binaries/commons-fileupload-1.0.zip
http://apache.freelamp.com/jakarta/commons/beanutils/binaries/commons-beanutils-1.7.0.zip
解压缩得到 commons-fileupload-1.0-beta-1.jar 和commons-beanutils.jar, 并将两个包放到 "YourWebApp/WEB-INF/lib"文件夹下。
UploadFile.java
package com.esurfer.common;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.text.SimpleDateFormat;
import java.io.*;
import org.apache.commons.fileupload.*;
public class UploadFile {
private String tmpdir;
private String updir;
private HttpServletRequest request;
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public String getTmpdir() {
return tmpdir;
}
public void setTmpdir(String string) {
tmpdir = string;
}
public String getUpdir() {
return updir;
}
public void setUpdir(String string) {
updir = string;
}
/**
* Create Directory with the name 'path'
* @param path
* @return
*/
private String MkDir(String path) {
String msg = null;
java.io.File dir;
// Create new file object
dir = new java.io.File(path);
if (dir == null) {
msg = "Error:<BR>Can't create empty directory!";
return msg;
}
if (dir.isFile()) {
msg = "Error:<BR>File name <B>" + dir.getAbsolutePath() +