struts2学习笔记(十) 利用fileUpload实现文件的上传

来源:百度文库 编辑:神马文学网 时间:2024/04/20 10:13:30
今天用struts2 的fileupload 实现了文件的上传。。
1 web.xml

xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

struts2
org.apache.struts2.dispatcher.FilterDispatcher


struts2
/*


index.jsp


2 struts.xml









/show.jsp
/index.jsp
/index.jsp


application/vnd.ms-powerpoint,image/bmp,image/png,image/gif,image/jpeg,image/pjpeg,image/jpg,application/msword,audio/x-mpeg,text/html,text/plain
8192000





3 action
package com.struts2.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private List file;
private List fileFileName;
private List fileContentType;
public List getFile() {
return file;
}
public void setFile(List file) {
this.file = file;
}
public List getFileContentType() {
return fileContentType;
}
public void setFileContentType(List fileContentType) {
this.fileContentType = fileContentType;
}
public List getFileFileName() {
return fileFileName;
}
public void setFileFileName(List fileFileName) {
this.fileFileName = fileFileName;
}
/**
* 动态上传文件
* @return
* @throws Exception
*/
public String Upload() throws Exception {
InputStream is=null;
OutputStream ops=null;
for(int i=0;itry{
is=new FileInputStream(file.get(i));
String root=ServletActionContext.getRequest().getRealPath("/uploads");
File destFile=new File(root+"/",this.getFileFileName().get(i));
//File destFile=new File(root,this.getFileFileName().get(i));
ops=new FileOutputStream(destFile);
byte [] b=new byte[400];
int length=0;
while((length=is.read(b))>0){
ops.write(b,0,length);
//ops.write(b); 这样子同样可行
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
is.close();
ops.close();
}
}
return "show";
}
}
4 jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="s" uri="/struts-tags" %>



My JSP 'upload.jsp' starting page




















选择上传的文件:

<%----%>









我试了下,上传成功,比较好用。
可以通过设置来设定上传文件的类型,8192000来设置上传文件的最大极限。