struts2上传文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2上传文件相关的知识,希望对你有一定的参考价值。
java代码:
package action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File upload;
private String uploadFileName;
private String uploadContentType;
public String doUpload() throws IOException{
/*System.out.println(upload);
System.out.println(uploadContentType);
System.out.println(uploadFileName);*/
String savePath = ServletActionContext
.getServletContext()
.getRealPath("/upload/"+this.uploadFileName);
System.out.println(savePath);
FileInputStream fis = new FileInputStream(upload);
FileOutputStream fos = new FileOutputStream(savePath);
IOUtils.copy(fis, fos);
fos.flush();
fos.close();
fis.close();
return SUCCESS;
}
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;
}
}
Struts2.xml配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ui.theme" value="simple"/>
<constant name="struts.multipart.maxSize" value="1000000" />
<constant name="struts.i18n.encoding" value="utf-8"/>
<package name="default" namespace="/" extends="struts-default">
<action name="doUpload" class="action.UploadAction"
method="doUpload">
<interceptor-ref name="fileUpload">
<param name="maximumSize">1000000</param>
<param name="allowedExtensions">jpg,jpeg,gif,png</param><!-- 也可以使用allowedTypes来控制上传的文件类型 -->
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<result>/singleSuccess.jsp</result>
<result name="input">/error.jsp</result>
</action>
</package>
</struts>
jsp:
<form action="doUpload" method="post"
enctype="multipart/form-data">
请选择文件:<input type="file" name="upload">
<input type="submit" value="上传文件">
</form>
以上是关于struts2上传文件的主要内容,如果未能解决你的问题,请参考以下文章