利用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值