码迷,mamicode.com
首页 > Web开发 > 详细

struts2上传文件

时间:2016-10-01 00:12:17      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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上传文件

标签:

原文地址:http://www.cnblogs.com/qiyc/p/5925051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!