三种文件上传组件代码

三种文件上传组件代码.

 commons-fileupload上传组件: 
(此组件还需要commons-io.jar)

public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  //上传文件工厂实例
  DiskFileItemFactory fileFactory = new DiskFileItemFactory();
  //上传文件存储路径
  String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
  //创建文件存放的仓库
  fileFactory.setRepository(new File(path));
  //设置缓存的大小(20M)
  fileFactory.setSizeThreshold(1024*1024*20);
  //用上传工厂实例创建上传文件对象
  ServletFileUpload fileUpload = new ServletFileUpload(fileFactory);
  fileUpload.setSizeMax(1024*1024*30);
  //fileUpload.setFileSizeMax(1024*1024*10);  //这句应该是设置单个文件大小的意思,但加上这句会失败. 
  //处理页面穿入的表单项
  List items = null;
  try {
   items = fileUpload.parseRequest(request);
  } catch (SizeLimitExceededException e) {
   request.setAttribute("errorInfo","上传文件超出30M");
   request.getRequestDispatcher("jsp/error.jsp").forward(request, response);
   return;
  } catch (FileUploadException e) {
   e.printStackTrace();
   request.setAttribute("errorInfo","上传出错");
   request.getRequestDispatcher("jsp/error.jsp").forward(request, response);
   return;
  }
  
  //遍历所有表单项
  for (int i = 0; i < items.size(); i++) {
   FileItem item = (FileItem)items.get(i);
   if ("".equals(item.getName())){//表示没有文件,这里暂时是通过文件名是否为空来判断是否有上传的文件的
    continue;
   }
   
   //如果这个表单是个普通表单域
   if (item.isFormField()){
    String name = item.getFieldName();
    String value = item.getString("utf-8");
    //将表单名和表单值传给页面
    request.setAttribute("name", name);
    request.setAttribute("value", value);
   } 
   //如果是文件域
   else {
    //获取文件域的表单域名
    String fieldName = item.getFieldName();
    //获取文件名
    String fileName = item.getName();
    //获取文件类型
    String contentType = item.getContentType();
    //对于上传文件的存放地址来建立一个输出流
    String newName = path + 
        (fileName.lastIndexOf(".") < 0 ? 
         fileName.substring(0, fileName.length()) : 
         System.currentTimeMillis() + fileName.substring(fileName.indexOf("."), fileName.length()));
    
    //判断上传文件是否在缓存之中
//这句可能表示上传的文件是否正在缓存向硬盘写入的过程中,但如果加上这句,会上传失败,不知为何...
//    if (item.isInMemory()){
     FileOutputStream output = new FileOutputStream(newName);
     InputStream input = item.getInputStream();
     byte[] buffer = new byte[1024];
     int len;
     while( (len = input.read(buffer)) > 0 ){
      output.write(buffer, 0, len);
     }
     input.close();
     output.flush();
     output.close();
//    }

    request.setAttribute("fieldName",fieldName);
    request.setAttribute("fileName",fileName);
    request.setAttribute("contentType",contentType);
   }
  }
  request.getRequestDispatcher("jsp/uploadResult.jsp").forward(request, response);
 }

 

COS上传组件:
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  //上传文件存储路径
  String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
  
  //设置上传文件最大限度
  MultipartParser mp = null;
  try {
   mp = new MultipartParser(request,1024*1024*10*2);
  } catch (Exception e) {
   request.setAttribute("errorInfo","上传文件失败");
   request.getRequestDispatcher("jsp/error.jsp").forward(request, response);
   return;
  }
  
  //代表一个file
  Part part = null;
  while((part = mp.readNextPart()) != null){
   //获取表单名
   String fieldName = part.getName();
   //如果是文件域
   if (part.isFile()){
    //取得上传的该文件
    FilePart filePart = (FilePart)part;
    String fileName = filePart.getFileName();
    if (fileName != null && !"".equals(fileName)){
     long size = filePart.writeTo(new File(path));//将文件写入硬盘
     
     request.setAttribute("fieldName",fieldName);
     request.setAttribute("fileName",fileName);
     request.setAttribute("contentType",filePart.getContentType());
    }
    //表示没有文件
    else {
     System.out.println("没有文件");
    }
   }
  }
  request.getRequestDispatcher("jsp/uploadResult.jsp").forward(request, response);
 }

 

SmartUpload组件:
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  
  //上传文件存储路径
  String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
  
  SmartUpload smtUpload = new SmartUpload();
  smtUpload.setForcePhysicalPath(true);
  smtUpload.initialize(this.getServletConfig(), request, response);
  
  //设置上传的每个文件的大小(10M) //这个能限制单个文件的大小
  smtUpload.setMaxFileSize(1024*1024*10);
  //设置上传的所有文件总大小(30M)
  smtUpload.setTotalMaxFileSize(1024*1024*10*3);
  //设置允许上传文件的格式
  smtUpload.setAllowedFilesList("jpg,gif,png,jpeg,bmp,JPG,GIF,PNG,JPEG,BMP,zip,rar,exe");
  
//  try {
//   //或者设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html,js扩展名的文件和没有扩展名的文件。
//   smtUpload.setDeniedFilesList("exe,bat,jsp,htm,html,js,,");
//  } catch (Exception e) {
//   e.printStackTrace();
//   request.setAttribute("errorInfo","禁止上传exe,bat,jsp,htm,html,js类型和空类型的文件");
//   request.getRequestDispatcher("jsp/error.jsp").forward(request,response);
//   return;
//  }
  try {
   smtUpload.upload(); //文件类型错误,文件大小错误的异常都是在这抛出的.
  } catch (Exception e){
   e.printStackTrace();
   request.setAttribute("errorInfo","文件上传错误,请检查上传的文件类型和大小");
   request.getRequestDispatcher("jsp/error.jsp").forward(request,response);
   return;
  }
  
  String fileName = "",fieldName="",contentType="";
  //上传文件
   for (int i = 0; i < smtUpload.getFiles().getCount(); i++) {
    com.jspsmart.upload.File file = smtUpload.getFiles().getFile(i);
    
    //如果该文件不为空
    if (!file.isMissing()) {
     fieldName = file.getFieldName();
     contentType=file.getContentType();
     try {
      fileName = file.getFileName();
       String suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
      String newFileName = System.currentTimeMillis() + suffix;//产生新的文件名
      System.out.println(path+newFileName);
      //保存文件
      file.saveAs(path + newFileName);
    } catch (Exception e) {
     e.printStackTrace();
     request.setAttribute("errorInfo","文件上传错误,请检查上传的文件类型");
     request.getRequestDispatcher("jsp/error.jsp").forward(request,response);
     return;
    }
    }
   }
   request.setAttribute("fieldName",fieldName);
  request.setAttribute("fileName",fileName);
  request.setAttribute("contentType",contentType);
   request.getRequestDispatcher("jsp/uploadResult.jsp").forward(request, response);
 }

 

upload.jsp:
<form action="<%=basePath %>/xxx.do" enctype="multipart/form-data" method="post">
   上传文件:

   <input type="file" name="Upload1" contenteditable="false" />
   


   <input type="file" name="Upload2" contenteditable="false" />
   


   <input type="file" name="Upload3" contenteditable="false" />
   


   <input type="submit" value="上传" />
  </form>

你可能感兴趣的:(html,jsp)