首先建立JSP页面 注意一定要有 enctype="multipart/form-data
<form name="f1" id="f1" action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
在建立action 很多人会不明白为什么 要写private String fileFileName 和 private String fileContentType; 注意我继承的是ActionSupport 里面有对这两个属性的配置 !
package com.upload.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUpload extends ActionSupport {
private File file;
private String fileFileName;
private String fileContentType;
@Override
public String execute() throws Exception {
// 得到上传的目录
String file_path = ServletActionContext.getServletContext().getRealPath("img");
System.out.println("文件路径"+file_path);
// 得到文件的后缀
String file_postfix = this.getFileFileName().substring(this.getFileFileName().lastIndexOf("."));
System.out.println("文件后缀"+file_postfix);
// 文件的全部信息
String file_full = file_path + File.separator+ System.currentTimeMillis() + file_postfix;
System.out.println("文件全程"+file_full);
// copy
File destFile = new File(file_full);
FileUtils.copyFile(this.getFile(), destFile);
return null;
}
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;
}
}
然后是配置文件:
<struts>
<constant name="struts.multipart.maxSize" value="2000000"></constant>
<package name="ad" extends="struts-default">
<action name="upload" class="com.upload.action.FileUpload">
</action>
</package>
</struts>