首页 > 代码库 > Struts 1 之文件上传

Struts 1 之文件上传

Struts 1 对Apache的commons-fileupload进行了再封装,把上传文件封装成FormFile对象

定义UploadForm:

private FormFilefile;       //上传的文件
private Stringtext;    //文件备注
//省略setter、getter
 

JSP:

<html:from action="/upload?method=upload" enctype="multipart/form-data">
 
文件:<html:file property="file"></html:file>
<br/>
备注:<html:textarea property="text"></html:textarea>
<br/>
<html:submit value=http://www.mamicode.com/”开始上传”/>>
 

处理上传操作的action:

 

UploadForm uploadForm = (UploadForm) form;
 
StringBuffer buffer = new StringBuffer();
 
if(uploadForm.getFile()!= null && uploadForm.getFile().getSize()>0){
      //获取文件夹/WEB-INF/classes
      File classes = new File(getClass().getClassLoader().getResource("").getFile());
     
      //获取文件夹/upload
      File uploadFolder = new File(classes.getParentFile().getParentFile(),"upload");
      uploadFolder.mkdirs();
 
      //保存到/upload文件夹下面
      File file = new File(uploadFolder, uploadForm.getFile().getFilename());
     
      OutputStreat ous = null;
      InputStream ins = null;
      try{
             byte [] byt = new byte [1024];
             int len = 0;
             ins =uploadForm.getFile().getInputStream();
             ous = new FileOutputStream(file);
             while((len = ins.read(byt))!=-1){
                    ous.write(byt,0,len);
             }
      }finally{
             ins.close();
             ous.close();
      }
      //点击即可下载
      buffer.append("文件:"+"<a href=http://www.mamicode.com/upload/>"+file.getName()+"target=_blank>"+file.getName()+"
");>

Struts 1 之文件上传