struts2实现文件上传
struts配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<!-- 常亮用来控制上传文件的大小 -->
<constant name="struts.multipart.maxSize" value="10240" />
<package name="upload" namespace="/" extends="frank_default" >
<!-- 上传文件start -->
<action name="upload" class="uploadAction" method="upload">
<interceptor-ref name="fileUpload">
<!-- 上传文件的类型 在这里起不到作用 ??????? -->
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png, image/pjpeg
</param>
<!-- 上传文件的大小限制 -->
<param name="maximumSize">512</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result type="json">
<param name="root">result</param>
</result>
</action>
<!-- 上传文件end -->
</package>
</struts>
jsp代码:
<div style="width: 400px;height: 200px;border: 5px solid red;padding: 15px;">
<form action="upload.do" method="post" id="upload" enctype="multipart/form-data"></form>
<input type="file" name="icon" form="upload" />
<input type="submit" value="上传" class="btn30" form="upload" />
<input type="text" name="age" />
<a href="upload.do">测试</a>
<div id="msg" style="display: none">正在上传。。。</div>
</div>
<script type="text/javascript">
// function upload(){
// $.ajax({
// url:"upload.do",
// method:"post",
// dataType:'json',
// async:true,//false:同步,true为异步(默认)
// beforeSend:function(xhr){
// $("#msg").css('display','block');
// },
// success:function(data){
// alert(data);
// $("#msg").css('display','none');
// alert("上传成功");
// }
// });
}
</script>
action代码:
package com.frank.server.bis.action;
import java.io.File;
import org.springframework.stereotype.Controller;
/**
*
*@descr:
*@className: UploadAction
*@author: frank
*@email: ws_post@163.com
*@date: Jan 17, 2014
*/
@Controller
public class UploadAction {
private boolean result = false;
private File icon; //上传的文件
private String iconFileName; //文件名称
private String iconContentType; //文件类型
public String upload(){
result = true;
System.out.println(icon);
System.out.println(getIconContentType());
return "success";
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public File getIcon() {
return icon;
}
public void setIcon(File icon) {
this.icon = icon;
}
public String getIconFileName() {
return iconFileName;
}
public void setIconFileName(String iconFileName) {
this.iconFileName = iconFileName;
}
public String getIconContentType() {
return iconContentType;
}
public void setIconContentType(String iconContentType) {
this.iconContentType = iconContentType;
}
}