论坛首页 Java企业应用论坛

Struts2的文件上传和下载

浏览 2818 次
该帖已经被评为隐藏帖
作者 正文
   发表时间:2009-03-05  
Struts2学习笔记
******Struts2的文件上传和下载******
*.文件上传90%struts帮我们做好了,我们只要大体上配一下就OK。

******不应用struts2,手工用fileuplaod上传******
*.是用第三文控件实现的,fileuplaod.
*.可选文件上传方式有三种:
1.apache-commons-FileUpload和IO两个包.
2.把两个JAR包考到工程的lib目录下。
*.文件上传两步:
1.<form>:method="post"
2.<form>:enctype="multipart/form-data"
*.fileuplaod包下面有:(fileuplaod包使用方法)org.apache.commons.fileupload.disk.DiskFileItemFactory类。(直接new出一个这样的工厂类。)
setRepository()方法:设置一个监时的目录,将一些大文件监时存放在这个目录里面。这样做不会占用很大的内存。
setSizeThreshold()方法:指定这个文件的大小,小于这个大小放入内存,超出这个大小放入硬盘。
org.apache.commons.fileupload.servlet.ServletFileUpload类,这个类是处理上传的。用DiskFileItemFactory生成的实例去构建ServletFileUpload实例。
parseRequest()方法:它会将从form传过来的所有东西无论是文件还是字符放在一个List里面,里面放的是FileItem接口。
isFormField()方法:一个boolean值来判断表单里的元素是否是文件类型的。
getInputStream()方法:获得文件的输入流。
代码:
DiskFileItemFactory factory = new DDiskFileItemFactory();
String path = request.getRealPath("/upload");
factory.setRepository(new File(path));
factory.setSizeThreshold(1024*1024);

ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list = upload.parseRequest(request);//try

for(FileItem item : list){
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString("gbk");
request.setAttribute(name, value);
}else{ //文件类型
String name = item.getFieldName();
String value = item.getName("gbk");
int start = value.lastIndexOf("/");
String fileName = value.substring(start + 1);
request.setAttribute(name,fileName);

item.write(new File(path,fileName));

/*用上面一句话可代替*/
//OutputStream os = new FileOutputStream(new File(path,fileName));
//InputStream is = item.getInputStream();
//byte[] buffer = new byte[400];
//int length = 0;
//while((length = is.read(buffer))>0){
// os.write(buffer,0,length);
//}
//os.close;is.colse();
}
}


******应用struts2,实现文件上传******
1.JSP引入struts2标签:<%@ taglic prefix="s" uri="/struts-tags"%>
2.<s:form action="upload" theme="simple" entcype="multipart/form-data">
3.file文件:<s:file name="file"></s:file>
4.在struts.xml文件里配<action name="upload" class="com.text.acion.UploadAction">
<result name="success">/uploadResult.jsp</result>
</action>
5.建一个UploadAction.java类:属性:
String username,password;
File file//和JSP页面的file相对应。
重:String fileFileName(文件名);fileContentType(文件类型);struts自动给我们注入进来。
6.在execute()里写:
InputStream is = new FileInputStream(file);
String root = ServletActionContext.getRequest().getRealPath("/upload");
File destFile = new File(root,this.getFileFileName());
outputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[400];
int length = 0;
while((length = is.read(buffer))>0){
os.write(buffer,0,length);
}
is.close();
os.close();
return success;
7.在成功JSP页面写:
username:<s:property value="username"/>
password:<S:property value="password"/>
file:<s:property value="fileFileName"/>
8.在strutsJAR包里:default.properties里有:struts.multipart.saveDir=(默认没有配值)我们要在struts.xml里配值:<constant name="struts.multipart.saveDir" value="C:/"></constant>
9.在strutsJAR包里:default.properties里有:struts.multipart.maxSize=2097152,也就是说文件大小默认2M,当然也可以是struts.xml里改。
******修改乱码:在struts.xml里*******
<constant name="struts.i18n.encoding" value="gbk"></constant>

*.上传指定多个文件,可用集合:
1.List<File> file
2.List<String> fileFileName;
3.List<String> fileContentType;
注:这三个集合的内容是一一对应的。
用for()循环读出来。
注:JSP文件上传的表单名都得一样。就都会映射到集合里面。

*.用户指定任意多个文件,做法:add,remove有JS代码:
function addMore(){
var td = document.getElementById("more");
var br = docunent.createElement("br");
var input = document.createElement("input");
var button = document.createElement("input");
input.type = "file";
input.name = "file";

button.type = "button";
button.value = "remove";
button.onclick = function(){
td.removeChild(br);
td.removechild(input);
td.removeChild(button);
}

td.appendChild(br);
td.appendChild(input);
td.appendChild(button);

}

****** struts2指定用户上传类型约束 ******
1.在Struts2的FileUploadInterceptor.java自已的拦截器中定义了maximumSize和alloedTypesSet这两个变量,maximumSize:实现了约束文件上传大小。alloedTypesSet:实现了可上传文件的类型。
2.在<action>标签中添加
<interceptor-ref name="fileupload">
<param name="maximumSize">409600</param>
<param name="alloedTypes">application/vnd.ms-powerpoint</param>
</interceptor-ref>
注:文件类型在tomcat-conf-web.xml里能找到,不用去记。
只要自已配了拦截器,默认拦截器一定要加上。
3.上传失败了struts2会放到一个fieldError里面。在页面用标签就可以输出。当然我们可以自定义去改其中的信息。
在struts-messages.properties里面有:struts.messgaes.error.content.type.not.allwed=;我们可以在全局的message.properties里去改他的值,复盖掉。
注:文件过大也是一样的道理。


****** struts2文件下载 ******
在Struts-default.xml里的返回类型result-type name="stream"。是有关文件下载的。
1、在DownloadAction.java里的代码:
public InputStream getDownloadFile(){
return ServletActionContext.getServletContext().getResourceAsStream("/upload/struts2.ppt");
}

public String execute() throws Exception{
return SUCCESS;
}
*.struts.xml里代码:
<action name="download" class="com.test.action.DownloadAction">
<result name="succcess" type="stream">
<param name="contenType">application/vnd.ms-powerpoint</param>
<param name="contentDisposition">filename="Struts2.ppt"</param>
</result>
<param name="inputName">downloadFile</param>
</action>
type的名字要和result-type里的名字一样。
注:<param name="inputName">downloadFile</param>里的downloadFile名字要和Action类里的public InputStream getDownloadFile()方法名一样。
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics