html代码
<form action="uploadfile.action" enctype="multipart/form-data" method="post">
<input type="file" name="mf">
<input type="submit" value="上传">
</form>
action代码
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
public class UploadAction {
private File mf;//临时的上传文件
private String mfFileName;//上传文件的真实名称
private String mfContentType;//上传文件的MIME类型
public String execute(){
// System.out.println(mf.getPath());
// System.out.println(mfFileName);
// System.out.println(mfContentType);
//将mf临时文件保存到目标位置
ServletContext application =
ServletActionContext.getServletContext();
//获取目标文件夹路径
String realPath =
application.getRealPath("/upload_images");
//获取目标文件实际路径
String filePath = realPath+File.separatorChar
+mfFileName;
//将mf复制到filePath
File destFile = new File(filePath);
copy(mf,destFile);
return "success";
}
private void copy(File srcFile,File destFile){
try{
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
byte[] bts = new byte[1024];
int len = -1;
while((len=fis.read(bts)) != -1){
fos.write(bts,0,len);
}
fis.close();
fos.flush();
fos.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
public File getMf() {
return mf;
}
public void setMf(File mf) {
this.mf = mf;
}
public String getMfContentType() {
return mfContentType;
}
public void setMfContentType(String mfContentType) {
this.mfContentType = mfContentType;
}
public String getMfFileName() {
return mfFileName;
}
public void setMfFileName(String mfFileName) {
this.mfFileName = mfFileName;
}
}