首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

struts2 file下传在简单代码

2012-09-21 
struts2 file上传在简单代码在jsp中:s:form actionprocess_task/process_task!upload themesimple

struts2 file上传在简单代码
在jsp中:

<s:form action="process_task/process_task!upload" theme="simple" method="post" enctype="multipart/form-data">
<table width="80%">
<tr>
<td>上传流程</td>
<td colspan="2"><s:file name="myFile" label="上传" theme="simple" ></s:file> <input type="submit" value="上传并获取任务"/></td>
</tr>
<table>

在action 中:
@Controller
@Result(name="success",type="chain",location="process_task")
public class ProcessTaskAction extends PersistAction<ProcessTask> {
private static final long serialVersionUID = -1496120091120103L;

private static final int BUFFER_SIZE = 16*1024;
    private File myFile;
private String contentType;
private String fileName;
private static String fileSite;
         
        public void setMyFileContentType(String contentType)  {
         this .contentType = contentType;
       }

        public void setMyFileFileName(String fileName)  {
         this .fileName = fileName;
   }

public File getMyFile() {
return myFile;
}

public void setMyFile(File myFile) {
this.myFile = myFile;
}

         /**
* 上传文件的方法
* @return 返回上传文件
*/
public String upload() {
if(fileName != null && !"".equals(fileName.trim())) {
String newFileName = new Date().getTime()+getExtention(fileName);
fileSite = ServletActionContext.getServletContext().getRealPath("/uploadXml")+"/"+newFileName;
File file = new File(fileSite);
copy(myFile,file);

}
return "list";

}
        /**
* 文件流的复制
* @param src 上传的源文件
* @param des 新建的文件
*/
private static void copy(File src, File des ) {
try {
InputStream in = null;
OutputStream out = null;

try {
     in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
             out = new BufferedOutputStream( new FileOutputStream(des), BUFFER_SIZE);
             byte[] bt =  new byte[BUFFER_SIZE];
             int length = 0;
             while((length = in.read(bt)) >0 ) {
            out.write(bt,0,length);
             }
} finally {
if(null != in) {
in.close();
}
if(null != out ) {
out.close();
}

}
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 获得上传文件名
* @return
*/
private static String getExtention(String fileName) {
String name= null;
if(fileName != null && !"".equals(fileName.trim())) {
int indext = fileName.lastIndexOf(".");
name = fileName.substring(indext);
}
return name;
}


}

热点排行