|
File[] file;
String[] fileFileName;
String[] fileContentType;
1、FileUploadAction的代碼
package cn.luxh.struts2.action;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 上傳檔案
* @author Luxh
*/
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 2642160699551232611L;
private static Log LOG = LogFactory.getLog(FileUploadAction.class);
protected File[] file;
protected String[] fileFileName;
protected String[] fileContentType;
/**
* 上傳檔案
*/
public String upload() {
try {
File[] files = uploadFile("/upload");
//獲得files後
//do some work
//...
}catch(Exception e) {
LOG.error("上傳檔案出錯!");
throw new RuntimeException("上傳檔案出錯");
}
return SUCCESS;
}
/**
* 處理上傳的檔案
* @param saveDir
* @return
* @throws IOException
*/
public File[] uploadFile(String saveDir) throws IOException {
if(saveDir==null ||"".equals(saveDir.trim())) {
saveDir = "/upload";
}
File[] files = null;
if(file != null && file.length > 0) {
String saveDirPath = ServletActionContext.getServletContext().getRealPath(saveDir);
File dirFile = new File(saveDirPath);
if(!dirFile.exists()) {
dirFile.mkdir();
}
files = new File[file.length];
for(int i=0;i<file.length;i++) {
if(file[i] != null) {
String newFileName = generateFileName(fileFileName[i]);
File destFile = new File(saveDirPath,newFileName);
FileUtils.copyFile(file[i], destFile);
}
}
}
return files;
}
/**
* 組建檔案名
* @param fileName
* @return
*/
private String generateFileName(String fileName) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String formatDate = sdf.format(new Date());
int position = fileName.lastIndexOf(".");
String extension = "";
if(position!=-1) {
extension = fileName.substring(position);
}
return formatDate + extension;
}
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getFileFileName() {
return fileFileName;
}
public void setFileFileName(String[] fileFileName) {
this.fileFileName = fileFileName;
}
public String[] getFileContentType() {
return fileContentType;
}
public void setFileContentType(String[] fileContentType) {
this.fileContentType = fileContentType;
}
}
2、上傳頁面upload.jsp
<form action="${pageContext.request.contextPath}/fileUpload/upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>
請選擇檔案:
</td>
</tr>
<tr>
<td>
<input type="file" name="file">
</td>
</tr>
<tr>
<td>
<input type="file" name="file">
</td>
</tr>
<tr>
<td>
<input type="file" name="file">
</td>
</tr>
</table>
<tr>
<td>
<input type="submit" value="Submit" id="submit">
</td>
</tr>
</form> |