利用ServletFileUpload组件上传文件

自己的运用:

public void UploadNoteFile(HttpServletRequest request,HttpServletResponse response){
  String path = request.getRealPath("/");
  String url = path + bean.getAttachPath();
  String savepath = new String (url);
   final long MAX_SIZE =Long.parseLong(bean.getAttachment())*1024;// 设置上传文件大小
   //  允许上传的文件格式的列表
    final String[] allowedExt = bean.getAttachType().split(",");
    long size = 0;  //文件大小
   try {
            request.setCharacterEncoding("gb2312");
            if(ServletFileUpload.isMultipartContent(request)){
                ServletFileUpload upload = new ServletFileUpload();
                upload.setSizeMax(MAX_SIZE);
                FileItemIterator iter = upload.getItemIterator(request);
                String subject="",content="";
                 while (iter.hasNext()) {
                     FileItemStream item = iter.next();
                     String name = item.getFieldName();
                     InputStream stream = item.openStream();        
                     if (item.isFormField()) {
                      //帖子标题
                      if(name.equals("subject")){   //获取subjec字段的值(非file字段)
                          subject=Streams.asString(stream);
                          continue;
                         }
                      //帖子详细内容
                      if(name.equals("message")){
                       content=Streams.asString(stream);
                       continue;
                      }
                      //获取控件值
                         System.out.println("控件名称" + name + " 值: "
                             + Streams.asString(stream));           
                     } else {
                      //上传附件
                      if(item.getName()!=null && !"".equals(item.getName())){
                          File file = new File(item.getName());
                          String filename = file.getName();
                          System.out.println("控件名称" + name + " 附件名称"
                              + filename);
                          // 得到去除路径的文件名
                          String t_name = url.substring(url.lastIndexOf("\\") + 1)+filename;
                          // 得到文件的扩展名(无扩展名时将得到全名)
                          String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); 
                         // 得到文件的大小
                         size =file.length();
                         if ("".equals(path) || size == 0) {
                          System.out.println("请选择上传文件<p />");
                          return;
                         }  
                         // 拒绝接受规定文件格式之外的文件类型
                         int allowFlag = 0;
                         int allowedExtCount = allowedExt.length;
                         for (; allowFlag < allowedExtCount; allowFlag++) {
                          if (allowedExt[allowFlag].equals(t_ext))
                           break;
                         }
                         if (allowFlag == allowedExtCount) {
                          System.out.println("请上传以下类型的文件<p />");
                           for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                            System.out.println("*." + allowedExt[allowFlag]);
                            return;
                          }
                          long now = System.currentTimeMillis();
                          // 根据系统时间生成上传后保存的文件名
                          String prefix = String.valueOf(now);
                          // 保存的最终文件完整路径
                           BufferedInputStream bis = new BufferedInputStream(stream);
                           BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(savepath + prefix + "." + t_ext)));
                           Streams.copy(bis, bos, true);
                           System.out.println("文件上传成功. 已保存为: " + prefix + "." + t_ext
                             + " &nbsp;&nbsp;文件大小: " + size + "字节<p />");
                      } 
                     }
                 } 
                 //发表新主题
                 addTopic(request,response,subject,content);
             }
        }
        catch(Exception e) {// 处理文件尺寸过大异常
            e.printStackTrace();
            if (e instanceof SizeLimitExceededException) {
              System.out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />");
              return;
             }
        }
     }

 

参考文章:http://qmug.javaeye.com/blog/225244

               http://ttitfly.javaeye.com/blog/158526

你可能感兴趣的:(fileupload)