前言
作为Struts2的初学者,首先使用一下Struts2,体会一下这个框架带来的方便。
1. ImageUploadForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h4>上传文件</h4>
<s:form action="ImageUpload" method="post"
enctype="multipart/form-data">
<s:file name="pic" label="Picture" />
<s:submit />
</s:form>
</body>
</html>
注:这是使用到了Struts2的标签库
2. ImageUpload.java
package example;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
public class ImageUpload extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
File pic;
String picContentType;
String picFileName;
private final Logger logger = LogManager.getFormatterLogger(this.getClass());
@Override
public String execute() throws Exception {
logger.debug(pic);
logger.debug(picContentType);
logger.debug(picFileName);
File myFile = new File("D:"+File.separator+picFileName);
logger.debug(pic.renameTo(myFile));
return super.execute();
}
public File getPic() {
return pic;
}
public void setPic(File pic) {
this.pic = pic;
}
public String getPicContentType() {
return picContentType;
}
public void setPicContentType(String picContentType) {
this.picContentType = picContentType;
}
public String getPicFileName() {
return picFileName;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
}
Method Signature | Description |
setX(File file) | The file that contains the content of the uploaded file. This is a temporary file and file.getName() will not return the original name of the file |
setXContentType(String contentType) | The mime type of the uploaded file |
setXFileName(String fileName) | The actual file name of the uploaded file (not the HTML name) |
3. example.xml
<action name="AddImage">
<result>/WEB-INF/jsp/example/ImageUploadForm.jsp</result>
</action>
<action name="ImageUpload" class="example.ImageUpload">
<result>/WEB-INF/jsp/example/ImageUploadForm.jsp</result>
<result name="input">/WEB-INF/jsp/example/ImageUploadForm.jsp</result>
</action>
4. execute方法
File myFile = new File("D:"+File.separator+picFileName);
logger.debug(pic.renameTo(myFile));
将文件保存在D盘的根目录下,仍使用原来的文件名。
5.效果
选择文件
完成