Struts 1 之文件上传

时间:2021-03-19 14:59:02

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=”开始上传”/>

</html:form>

处理上传操作的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=upload/>"+file.getName()+"target=_blank>"+file.getName()+"</a><br/>");
}else{
      buffer.append("没有选择文件!<br/>");
}
buffer.append("备注:"+ uploadForm.getText()+"<br/>");
response.setCharacterEncoding("UTF-8");
response.getWriter().writer(buffer.toString());