建立 java.io.File 類型的欄位來接收上傳的檔案流;建立 xxxFileName 和 xxxContentType 來讀取原始上傳的檔案名稱和檔案類型,其中 xxx 表示的是 java.io.File 類型的欄位名稱,比如樣本是名為 upload 欄位接收上傳的檔案流,因此需要有 uploadFileName 和 uploadContentType 來接收該檔案流的原始檔案名稱和檔案類型,範例程式碼如下:??
public class UploadAction extends ActionSupport {
??
/**
*
*/
private static final long serialVersionUID = 283051583917637792L;
??
private File upload;
private String uploadFileName;
private String uploadContentType;
private String uploadPath;
??
public UploadAction() {
uploadPath = "upload";
}
??
@Override
public String execute() throws Exception {
??
if (upload == null) {
addActionError("沒有選擇上傳檔案");
return INPUT;
}
??
String filePath = ServletActionContext.getServletContext().getRealPath(uploadPath);
??
java.io.File dir = new java.io.File(filePath);
if (dir.exists() == false) {
if (dir.mkdirs() == false) {
addActionError("建立目錄失敗,目錄路徑=" + filePath);
return INPUT;
}
}
??
System.out.println("Upload FileName =" + uploadFileName);
System.out.println("Upload ContentType =" + uploadContentType);
??
FileOutputStream fileOutputStream = new FileOutputStream(filePath + File.pathSeparator + uploadFileName);
FileInputStream fileInputStream = new FileInputStream(upload);
byte[] buffer = new byte[4096];
int len = 0;
do {
len = fileInputStream.read(buffer, 0, buffer.length);
if (len > 0) {
fileOutputStream.write(buffer, 0, len);
}
} while (len > 0);
??
addActionMessage("上傳完成,儲存路徑=" + filePath + File.pathSeparator + uploadFileName);
??
return SUCCESS;
}
??
public File getUpload() {
return upload;
}
??
public void setUpload(File upload) {
this.upload = upload;
}
??
public String getUploadFileName() {
return uploadFileName;
}
??
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
??
public String getUploadContentType() {
return uploadContentType;
}
??
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
}