标签:
具体步骤:完整代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'fileUpload.jsp' starting page</title>
</head>
<body>
<form
action="${pageContext.request.contextPath}/control/list_execute.action"
enctype="multipart/form-data" method="post">
文件:<input type="file" name="uploadfile"> <input type="submit"
value="上传" />
</form>
</body>
</html>
package struts2.example.action;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class HelloWorldAction {
private File uploadfile;
private String uploadfileFileName;// 上传文件的文件名称
public File getUploadfile() {
return uploadfile;
}
public void setUploadfile(File uploadfile) {
this.uploadfile = uploadfile;
}
public String getUploadfileFileName() {
return uploadfileFileName;
}
public void setUploadfileFileName(String uploadfileFileName) {
this.uploadfileFileName = uploadfileFileName;
}
public String execute() {
// 得到站点下files文件夹的绝对路径
String realpath = ServletActionContext.getServletContext().getRealPath(
"/files");
System.out.print(realpath);
if (uploadfile != null) {
/*
* 参数1:文件保存的目录 参数2:文件保存的文件名
*/
File saveFile = new File(new File(realpath), uploadfileFileName);
// 用saveFile.getParentFile()得到目录,如果目录不存在,则创建该目录
if (!saveFile.getParentFile().exists())
saveFile.getParentFile().mkdirs();
// 对文件进行保存
try {
FileUtils.copyFile(uploadfile, saveFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ActionContext.getContext().put("upload_success", "文件上传成功!");
}
return "success";
}
}
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.multipart.maxSize" value="10701096" />
<package name="csdn" namespace="/control" extends="struts-default">
<action name="list_*" class="struts2.example.action.HelloWorldAction"
method="{1}">
<!-- 定义处理结果与视图资源之间的关系 -->
<result name="success">/WEB-INF/page/showInfo.jsp</result>
</action>
</package>
</struts>
<constant name="struts.multipart.maxSize" value="10701096">
如果上传的文件过大,如上百兆,应通过应用软件上传,通过web上传不稳定。
标签:
原文地址:http://blog.csdn.net/lindonglian/article/details/46575067