自己总结一下STRUTS上传图片

一下三个方法:

private boolean fileGeshi(String fname) {
  // *************限制非图片文件的上传*******************
  String fileType = (fname.substring(fname.lastIndexOf('.') + 1))
    .toLowerCase();
  if ((!fileType.equals("jpg")) && (!fileType.equals("bmp"))
    && (!fileType.equals("gif")) && (!fileType.equals("jpeg"))) {
   // errors.add("filetype",new ActionError("error.file.type"));
   // saveErrors(request,errors);
   return false;
  }
  return true;
 }

 private boolean fileDAx(int size) {
  // *************限制文件不能超过2M******************
  if (size > 2097152) {
   // errors.add("size",new ActionError("error.file.size"));
   // saveErrors(request,errors);
   // return (new ActionForward(mapping.getInput()));
   return false;
  }
  return true;
 }

 /**
  * 上传文件
  *
  * @param fileName
  * @param is
  * @throws IOException
  */

 private void uploadFile(String filePath, String fileName, InputStream is)
   throws IOException {
  OutputStream os = new FileOutputStream(filePath + fileName);
  // 8k缓存数据
  byte[] buffer = new byte[1024 * 8];
  // 设置读进缓存的字节数
  int len;
  while ((len = is.read(buffer)) != -1) {
   // 将缓存数据写入磁盘
   os.write(buffer, 0, len);
  }
  // 关闭输出流
  os.close();
  // 关闭输入流
  is.close();
 }

 

ACTION中部分代码:

InfoTips tips=new InfoTips();
   FormFile file = ArticleForm.getFILE1();

   String filePath = this.getServlet().getServletContext()
     .getRealPath("/");
   // 得到文件名
   String fileName = file.getFileName();
   // 得到文件大小
   int fileSize = file.getFileSize();
   System.out.println("FileName = " + fileName);
   System.out.println("FileSize=" + fileSize);

   filePath = filePath + "UploadFile//";
   try {
    if (fileSize != 0) {
     if (fileGeshi(fileName)) {
      if (fileDAx(fileSize)) {
       InputStream is = file.getInputStream();
       // 上传文件
       uploadFile(filePath, fileName, is);
      }
      else{
       tips.setTipsInfo("图片大小超出2M,请重新上传");
       request.setAttribute("ErrorTip", tips);
       return mapping.findForward("admin/articleadd");
      }
     }
     else{
      tips.setTipsInfo("图片格式不正确,请重新上传");
      request.setAttribute("ErrorTip", tips);
      return mapping.findForward("admin/articleadd");
     }
    }

   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

你可能感兴趣的:(exception,struts,String,buffer,action,byte)