67,513
社区成员
发帖
与我相关
我的任务
分享
<struts>
<constant name="struts.action.extension" value="do" />
<constant name="struts.i18n.encoding" value="GBK" />
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="true" />
<package name="con.duoyide" extends="struts-default">
<action name="fileUpload"
class="com.duoyide.action.FileAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" pageEncoding="GBK"%>
<html>
<head>
<title>Struts2 File Upload</title>
</head>
<body>
<form action="fileUpload.do" method="POST"
enctype="multipart/form-data">
文件标题:
<input type="text" name="title" size="50" />
<br />
选择文件:
<input type="file" name="upload" size="50" />
<br />
<input type="submit" value=" 上传 " />
</form>
</body>
</html>
public class FileAction extends ActionSupport {
private static final long serialVersionUID = 1189106219658323341L;
public static final int BUFFER_SIZE = 16 * 1024;
// 文件标题
private String title;
// 上传文件域对象
private File upload;
// 上传文件名
private String uploadFileName;
// 上传文件类型
private String uploadContentType;
// 保存文件的目录路径(通过依赖注入)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
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;
}
@Override
public String execute() throws Exception {
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
ServletContext svct = ServletActionContext.getServletContext();
System.out.println(upload);
if (upload != null) {
String dataDir = svct.getRealPath("/upload");
File saveFile = new File(dataDir, title);
upload.renameTo(saveFile);
}
return SUCCESS;
}
}