文件上传准备:
注意:
表单必须使用POST方式提交;(get方式太小)
使用二进制编码.multipart/form-data(把文件的数据发给服务端而不是文件的名称)
<input type="file" name=""/> --> <s:file>
public class UploadAction extends ActionSupport {
private String username;
private File headImg;//上传的文件对象
private String headImgFileName;//上传文件的名称
private String headImgContentType;//上传文件的MIME类型
public void setHeadImgFileName(String headImgFileName) {
this.headImgFileName = headImgFileName;
}
public void setHeadImgContentType(String headImgContentType) {
this.headImgContentType = headImgContentType;
}
public void setHeadImg(File headImg) {
this.headImg = headImg;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String execute() throws Exception {
System.out.println(username);
// System.out.println(headImg);
// System.out.println(headImgFileName);
// System.out.println(headImgContentType);
//获取保存上传文件的目录
// String dir = "E:\\intellij IDEA\\Struts2-day03\\web\\upload";
String dir = ServletActionContext.getServletContext().getRealPath("/upload");
//构建上传文件的目录和名称
File destFile = new File(dir,headImgFileName);
//文件内容的拷贝
FileUtils.copyFile(headImg,destFile);
return NONE;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<s:form action="upload" namespace="/upload" method="" enctype="multipart/form-data">
<s:textfield name="username" label="姓名:"></s:textfield>
<s:file name="headImg" label="头像" ></s:file>
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>