Example #1
0
 public void upload() throws Exception {
   boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
   if (!isMultipart) {
     this.state = this.errorInfo.get("NOFILE");
     return;
   }
   DiskFileItemFactory dff = new DiskFileItemFactory();
   String savePath = this.getFolder(this.savePath);
   dff.setRepository(new File(savePath));
   try {
     ServletFileUpload sfu = new ServletFileUpload(dff);
     sfu.setSizeMax(this.maxSize * 1024);
     sfu.setHeaderEncoding("utf-8");
     FileItemIterator fii = sfu.getItemIterator(this.request);
     while (fii.hasNext()) {
       FileItemStream fis = fii.next();
       if (!fis.isFormField()) {
         this.originalName =
             fis.getName()
                 .substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
         if (!this.checkFileType(this.originalName)) {
           this.state = this.errorInfo.get("TYPE");
           continue;
         }
         this.fileName = this.getName(this.originalName);
         this.type = this.getFileExt(this.fileName);
         this.url = savePath + "/" + this.fileName;
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url)));
         BufferedOutputStream output = new BufferedOutputStream(out);
         Streams.copy(in, output, true);
         this.state = this.errorInfo.get("SUCCESS");
         // UE中只会处理单张上传,完成后即退出
         break;
       } else {
         String fname = fis.getFieldName();
         // 只处理title,其余表单请自行处理
         if (!fname.equals("pictitle")) {
           continue;
         }
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
         StringBuffer result = new StringBuffer();
         while (reader.ready()) {
           result.append((char) reader.read());
         }
         this.title = new String(result.toString().getBytes(), "utf-8");
         reader.close();
       }
     }
   } catch (SizeLimitExceededException e) {
     this.state = this.errorInfo.get("SIZE");
   } catch (InvalidContentTypeException e) {
     this.state = this.errorInfo.get("ENTYPE");
   } catch (FileUploadException e) {
     this.state = this.errorInfo.get("REQUEST");
   } catch (Exception e) {
     this.state = this.errorInfo.get("UNKNOWN");
   }
 }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    // 设置上传文件大小的上限,-1表示无上限
    fileUpload.setSizeMax(-1);
    // 上传文件,解析表单中包含的文件字段和普通字段
    try {
      List<FileItem> items = fileUpload.parseRequest(request);
      if (items.size() > 0) {
        FileItem item = (FileItem) items.get(0);
        String name = item.getName();
        String path = getServletContext().getRealPath(Constants.UPLOAD_IMG_PATH) + "/" + name;
        logger.info("上传用户图片信息,图片名:" + name + ";上传路径:" + path);
        // 实现图片上传
        try {
          item.write(new File(path));
          // 就用户头像路径保存.
          User user = new User();
          user.setPhone(request.getHeader("owner"));
          user.setImgPath(Constants.UPLOAD_IMG_PATH + "/" + name);
          userService.saveOrUpdateUserInfo(user);

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

    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #3
0
  private void parseParams() {

    DiskFileItemFactory dff = new DiskFileItemFactory();
    try {
      ServletFileUpload sfu = new ServletFileUpload(dff);
      sfu.setSizeMax(this.maxSize);
      sfu.setHeaderEncoding(Uploader.ENCODEING);

      FileItemIterator fii = sfu.getItemIterator(this.request);

      while (fii.hasNext()) {
        FileItemStream item = fii.next();
        // 普通参数存储
        if (item.isFormField()) {

          this.params.put(item.getFieldName(), this.getParameterValue(item.openStream()));

        } else {

          // 只保留一个
          if (this.inputStream == null) {
            this.inputStream = item.openStream();
            this.originalName = item.getName();
            return;
          }
        }
      }

    } catch (Exception e) {
      this.state = this.errorInfo.get("UNKNOWN");
    }
  }
 private List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir)
     throws FileUploadException {
   DiskFileItemFactory fac = createDiskFileItemFactory(saveDir);
   ServletFileUpload upload = new ServletFileUpload(fac);
   upload.setSizeMax(maxSize);
   return upload.parseRequest(createRequestContext(servletRequest));
 }
Example #5
0
 @Override
 protected void service() throws ServletException, IOException {
   HttpServletRequest request = getRequest();
   String path = null;
   DiskFileItemFactory factory =
       new DiskFileItemFactory(5 * 1024, new File(Configuration.getContextPath("temp")));
   ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setSizeMax(3 * 1024 * 1024);
   try {
     List<FileItem> items = upload.parseRequest(request);
     FileItem fileItem = null;
     if (items != null
         && items.size() > 0
         && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
       String fileName = fileItem.getName();
       if (!fileName.endsWith(".jpg")
           && !fileName.endsWith(".gif")
           && !fileName.endsWith(".png")) {
         writeText("format_error");
         return;
       }
       path = ImageUtil.generatePath(fileItem.getName());
       IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
       fileItem.delete();
       writeText(Configuration.getSiteUrl(path));
     }
   } catch (FileUploadException e) {
     throw new RuntimeException(e);
   }
 }
  public void upload(
      @Observes ControllerFound event,
      MutableRequest request,
      MultipartConfig config,
      Validator validator) {

    if (!ServletFileUpload.isMultipartContent(request)) {
      return;
    }

    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    final Multiset<String> indexes = HashMultiset.create();
    final Multimap<String, String> params = LinkedListMultimap.create();

    ServletFileUpload uploader = createServletFileUpload(config);

    UploadSizeLimit uploadSizeLimit =
        event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class);
    uploader.setSizeMax(
        uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit());
    uploader.setFileSizeMax(
        uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit());
    logger.debug(
        "Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax());

    try {
      final List<FileItem> items = uploader.parseRequest(request);
      logger.debug(
          "Found {} attributes in the multipart form submission. Parsing them.", items.size());

      for (FileItem item : items) {
        String name = item.getFieldName();
        name = fixIndexedParameters(name, indexes);

        if (item.isFormField()) {
          logger.debug("{} is a field", name);
          params.put(name, getValue(item, request));

        } else if (isNotEmpty(item)) {
          logger.debug("{} is a file", name);
          processFile(item, name, request);

        } else {
          logger.debug("A file field is empty: {}", item.getFieldName());
        }
      }

      for (String paramName : params.keySet()) {
        Collection<String> paramValues = params.get(paramName);
        request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
      }

    } catch (final SizeLimitExceededException e) {
      reportSizeLimitExceeded(e, validator);

    } catch (FileUploadException e) {
      reportFileUploadException(e, validator);
    }
  }
 private static ServletFileUpload createFileUpload() {
   ServletFileUpload upload =
       new ServletFileUpload(
           new DiskFileItemFactory(IN_MEMORY_FILE_SIZE_THRESHOLD, new File(TMP_DIR)));
   upload.setSizeMax(MAX_UPLOAD_FILE_SIZE);
   return upload;
 }
Example #8
0
  @SuppressWarnings("null")
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    //
    if (!isMultipart) {
      return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    // factory.setRepository(new File("d:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    // System.out.println(empid);
    try {
      // out = response.getWriter( );
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
          // Get the uploaded file parameters
          String fieldName = fi.getFieldName();
          String fileName = fi.getName();
          String contentType = fi.getContentType();
          boolean isInMemory = fi.isInMemory();
          long sizeInBytes = fi.getSize();
          // Write the file
          if (fileName.lastIndexOf("\\") >= 0) {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
          } else {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
          }
          fi.write(file);
          readBOM(file);
          break;
        }
      }
      RequestDispatcher ReqDis = request.getRequestDispatcher("afterBOM.jsp");
      ReqDis.forward(request, response);

    } catch (Exception ex) {
      ex.printStackTrace();

      RequestDispatcher ReqDis = request.getRequestDispatcher("Error.jsp");
      ReqDis.forward(request, response);
    }
  }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    System.out.println("开始!" + fileName);

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxPostSize);

    try {
      String rootPath = request.getRealPath("/");
      String filePath = rootPath + uploadPath;

      // 若该路径目录不存在,则创建
      File f = new File(filePath);
      if (!f.exists()) {
        f.mkdirs();
      }

      File f2 = new File(filePath + File.separator + fileName + ".jpg");
      if (f2.exists()) {
        out.print("文件已存在");
      } else {
        InputStream inputStream = request.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(f2);

        try {
          int formlength = request.getContentLength();
          byte[] formcontent = new byte[formlength];
          int totalread = 0;
          int nowread = 0;
          while (totalread < formlength) {
            nowread = inputStream.read(formcontent, totalread, formlength);
            totalread += nowread;
          }

          outputStream.write(formcontent);
          outputStream.flush();
        } catch (IOException e) {
          e.printStackTrace();
          out.print("错误:" + e.getMessage());
        } finally {
          outputStream.close();
          inputStream.close();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      out.print("错误:" + e.getMessage());
    } finally {
      out.close();
    }
    System.out.println("结束");
  }
Example #10
0
 /**
  * Utility method for parsing a multipart servlet request. This method returns an iterator of
  * FileItem objects that corresponds to the request.
  *
  * @param request The servlet request containing the multipart request.
  * @return Returns an iterator of FileItem objects the corresponds to the request.
  * @throws Exception Thrown if any problems occur while processing the request.
  */
 protected static Iterator processMultipartRequest(HttpServletRequest request) throws Exception {
   // Create a factory for disk-based file items
   DiskFileItemFactory factory = new DiskFileItemFactory();
   factory.setRepository(new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH)));
   ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setHeaderEncoding("UTF-8");
   upload.setSizeMax(Environment.getLongValue(Environment.PROP_FILE_MAX_FILE_SIZE));
   return upload.parseRequest(request).iterator();
 }
Example #11
0
  /** 上传ruleset */
  public void upRuleset() throws Exception {
    /**
     * form中的enctype必须是multipart/... 组件提供方法检测form表单的enctype属性 在isMultipartContent方法中同时检测了是否是post提交
     * 如果不是post提交则返回false
     */
    if (ServletFileUpload.isMultipartContent(request)) {
      String RulePath = (String) application.getAttribute("Ruleset");
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setRepository(new File(RulePath + "tmp")); // 临时文件目录
      // 内存最大占用
      factory.setSizeThreshold(1024000);
      ServletFileUpload sfu = new ServletFileUpload(factory);
      // 单个文件最大值byte
      sfu.setFileSizeMax(102400000);
      // 所有上传文件的总和最大值byte
      sfu.setSizeMax(204800000);

      List<FileItem> items = null;
      try {
        items = sfu.parseRequest(request);
      } catch (SizeLimitExceededException e) {
        error("size limit exception!");
        return;
      } catch (Exception e) {
        error("Exception:" + e.getMessage());
        return;
      }

      Json j = new Json(1, "ok");
      JsonObjectNode data = j.createData();
      JsonArrayNode files = new JsonArrayNode("filename");
      data.addChild(files);

      Iterator<FileItem> iter = (items == null) ? null : items.iterator();
      while (iter != null && iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        // 文件域
        if (!item.isFormField()) {
          String fileName = item.getName();
          int index = fileName.lastIndexOf("\\");
          if (index < 0) index = 0;
          fileName = fileName.substring(index);
          if (!fileName.endsWith(".xml")) fileName += ".xml";
          BufferedInputStream in = new BufferedInputStream(item.getInputStream());
          BufferedOutputStream out =
              new BufferedOutputStream(new FileOutputStream(new File(RulePath + fileName)));
          Streams.copy(in, out, true);
          files.addItem(new JsonLeafNode("", fileName));
        }
      }

      echo(j.toString());
    } else {
      error("enctype error!");
    }
  }
Example #12
0
  /**
   * The doPost method of the servlet. <br>
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    // InputStream is =  request.getInputStream();

    // InputStreamReader isr = new InputStreamReader(is);
    // char[] c = new char[100];
    // while(isr.read(c)!=-1){
    //	System.out.println(c);
    // }

    String path = request.getRealPath("/");
    String savePath = path + "file\\";
    String tempPath = path + "temp\\";
    File f = new File(tempPath);
    // byte[] b = new byte[1];
    // int len = 0;
    // while((len=is.read(b))!=-1){
    //	fos.write(b,0,len);
    // }
    // fos.flush();
    // fos.close();
    // is.close();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(f);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1024 * 1024 * 1024);
    List<FileItem> items = new ArrayList<FileItem>();
    try {
      items = upload.parseRequest(request);
    } catch (FileUploadException e) {
      e.printStackTrace();
    }
    for (FileItem fileItem : items) {
      System.out.println(fileItem.getName());
      System.out.println(fileItem.getFieldName());
      System.out.println(fileItem.getSize());
      InputStream is = fileItem.getInputStream();
      FileOutputStream fos = new FileOutputStream(savePath + fileItem.getName());
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = is.read(b)) != -1) {
        fos.write(b, 0, len);
      }
      fos.flush();
      fos.close();
      is.close();
    }
  }
Example #13
0
  static {
    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    upload = new ServletFileUpload(factory);
    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);
  }
Example #14
0
 /** <b>这个不能用,他用的是apache的FileUpload</b> 功能描述:使用fileupload components 上传多个文件 */
 public List<Map> UploadFilesByFileupload(HttpServletRequest request) {
   boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   List<Map> resultList = new ArrayList<Map>();
   if (!isMultipart) {
     return resultList;
   }
   String userfilepath = request.getRealPath("upload");
   DiskFileItemFactory factory = new DiskFileItemFactory();
   factory.setSizeThreshold(2 * 1024 * 1024); // 2MB
   factory.setRepository(new File(userfilepath));
   ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setSizeMax(50 * 1024 * 1024); // 50MB
   try {
     List<FileItem> items = upload.parseRequest(request);
     for (FileItem item : items) {
       if (item.isFormField()) {
         // 普通表单
       } else {
         String fieldName = item.getFieldName();
         String fileName = item.getName();
         // 如果文件域没有填写内容,或者填写的文件不存在
         if ("".equals(fileName) || item.getSize() == 0) {
           continue;
         }
         String date = "/" + fnu.getDate8() + "/";
         String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
         String newfilename = fnu.getUUID() + "." + extName;
         File uploadedFile = new File(userfilepath + date + newfilename);
         if (!uploadedFile.exists()) { // 如果要写入的文件或目录不存在,那么试着创建要写入的目录,以便写入文件
           uploadedFile.getParentFile().mkdirs();
         }
         item.write(uploadedFile);
         Map tmpfile = new HashMap<String, String>();
         tmpfile.put("fieldname", fieldName);
         tmpfile.put(
             "filename",
             fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length()));
         tmpfile.put("extname", extName);
         tmpfile.put("filepath", "/upload" + date + newfilename);
         resultList.add(tmpfile);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return resultList;
 }
  public int populateImagesFromDatabase(
      HttpServletRequest request, HttpServletResponse response, List<DemoProductInfo> products)
      throws ServletException, IOException {
    final String IMAGE_DIRECTORY = "img";
    final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
    final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    // set variables to provide path names and scope visibility through method
    String fileName = null;
    int numFilesWritten = 0;

    // configures file writing settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // use factory to provide thread-safe retrieval mechanism to
    // write to eventual application directory
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("") + File.separator + IMAGE_DIRECTORY;

    // in this case use a predetermined path set at start of method
    // String uploadPath = uploadToDirPath;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
      uploadDir.mkdir();
    }

    for (DemoProductInfo product : products) {
      String filePath = uploadPath + File.separator + product.getFilename();
      DemoProductInfoDB.getBytesToFile(product.getProductImage(), filePath);
      numFilesWritten++;
    }

    return numFilesWritten;
  }
  /**
   * Pseudo-constructor that allows the class to perform any initialization necessary.
   *
   * @param request an HttpServletRequest that has a content-type of multipart.
   * @param tempDir a File representing the temporary directory that can be used to store file parts
   *     as they are uploaded if this is desirable
   * @param maxPostSize the size in bytes beyond which the request should not be read, and a
   *     FileUploadLimitExceeded exception should be thrown
   * @throws IOException if a problem occurs processing the request of storing temporary files
   * @throws FileUploadLimitExceededException if the POST content is longer than the maxPostSize
   *     supplied.
   */
  @SuppressWarnings("unchecked")
  public void build(HttpServletRequest request, File tempDir, long maxPostSize)
      throws IOException, FileUploadLimitExceededException {
    try {
      this.charset = request.getCharacterEncoding();
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setRepository(tempDir);
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setSizeMax(maxPostSize);
      List<FileItem> items = upload.parseRequest(request);
      Map<String, List<String>> params = new HashMap<String, List<String>>();

      for (FileItem item : items) {
        // If it's a form field, add the string value to the list
        if (item.isFormField()) {
          List<String> values = params.get(item.getFieldName());
          if (values == null) {
            values = new ArrayList<String>();
            params.put(item.getFieldName(), values);
          }
          values.add(charset == null ? item.getString() : item.getString(charset));
        } // Else store the file param
        else {
          files.put(item.getFieldName(), item);
        }
      }

      // Now convert them down into the usual map of String->String[]
      for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        List<String> values = entry.getValue();
        this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
      }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
      throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
      IOException ioe = new IOException("Could not parse and cache file upload data.");
      ioe.initCause(fue);
      throw ioe;
    }
  }
Example #17
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String saveFilename = null;
    String realSavePath = null;
    String filename = null;

    Users users = (Users) request.getSession().getAttribute("loginuser");
    int sid = users.getIdusers();

    // 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
    String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
    // 上传时生成的临时文件保存目录
    String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
    File tmpFile = new File(tempPath);
    if (!tmpFile.exists()) {
      // 创建临时目录
      tmpFile.mkdir();
    }

    // 消息提示
    String message = "";
    try {
      // 使用Apache文件上传组件处理文件上传步骤:
      // 1、创建一个DiskFileItemFactory工厂
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // 设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
      factory.setSizeThreshold(1024 * 100); // 设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
      // 设置上传时生成的临时文件的保存目录
      factory.setRepository(tmpFile);
      // 2、创建一个文件上传解析器
      ServletFileUpload upload = new ServletFileUpload(factory);
      // 监听文件上传进度
      upload.setProgressListener(
          new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int arg2) {
              System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
              /**
               * 文件大小为:14608,当前已处理:4096 文件大小为:14608,当前已处理:7367 文件大小为:14608,当前已处理:11419
               * 文件大小为:14608,当前已处理:14608
               */
            }
          });
      // 解决上传文件名的中文乱码
      upload.setHeaderEncoding("gb2312");
      // 3、判断提交上来的数据是否是上传表单的数据
      if (!ServletFileUpload.isMultipartContent(request)) {
        // 按照传统方式获取数据
        return;
      }

      // 设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB
      upload.setFileSizeMax(1024 * 1024);
      // 设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB
      upload.setSizeMax(1024 * 1024 * 10);
      // 4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
      List<FileItem> list = upload.parseRequest(request);
      for (FileItem item : list) {
        // 如果fileitem中封装的是普通输入项的数据
        if (item.isFormField()) {
          String name = item.getFieldName();
          // 解决普通输入项的数据的中文乱码问题
          String value = item.getString("gb2312");
          // value = new String(value.getBytes("iso8859-1"),"UTF-8");
          System.out.println(name + "=" + value);
        } else { // 如果fileitem中封装的是上传文件
          // 得到上传的文件名称,
          filename = item.getName();
          System.out.println(filename);
          if (filename == null || filename.trim().equals("")) {
            continue;
          }
          // 注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
          // 处理获取到的上传文件的文件名的路径部分,只保留文件名部分
          filename = filename.substring(filename.lastIndexOf("\\") + 1);
          // 得到上传文件的扩展名
          String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
          // 如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法
          System.out.println("上传的文件的扩展名是:" + fileExtName);
          // 获取item中的上传文件的输入流
          InputStream in = item.getInputStream();
          // 得到文件保存的名称
          saveFilename = makeFileName(filename);
          // 得到文件的保存目录
          realSavePath = makePath(saveFilename, savePath);
          // 创建一个文件输出流
          FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
          // 创建一个缓冲区
          byte buffer[] = new byte[1024];
          // 判断输入流中的数据是否已经读完的标识
          int len = 0;
          // 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
          while ((len = in.read(buffer)) > 0) {
            // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
            out.write(buffer, 0, len);
          }
          // 关闭输入流
          in.close();
          // 关闭输出流
          out.close();
          // 删除处理文件上传时生成的临时文件
          // item.delete();
          message = "文件上传成功!";

          Files files = new Files();
          files.setFilename(filename);
          files.setFileonlyname(saveFilename);
          files.setFilesroute(realSavePath);

          FileDao fileDao = new FileDao();
          fileDao.addOne(files, sid);
        }
      }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
      e.printStackTrace();
      request.setAttribute("message", "单个文件超出最大值!!!");
      request.getRequestDispatcher("user_view/file/file_message.jsp").forward(request, response);
      return;
    } catch (FileUploadBase.SizeLimitExceededException e) {
      e.printStackTrace();
      request.setAttribute("message", "上传文件的总的大小超出限制的最大值!!!");
      request.getRequestDispatcher("user_view/file/file_message.jsp").forward(request, response);
      return;
    } catch (Exception e) {
      message = "文件上传失败!";
      e.printStackTrace();
    }

    request.setAttribute("message", message);
    request.getRequestDispatcher("/user_view/file/file_message.jsp").forward(request, response);
  }
Example #18
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    boolean isMultipart = FileUpload.isMultipartContent(req);
    Hashtable dv = new Hashtable();
    String user = null;
    String password = null;
    String sql = null;
    String dfo = null;
    String enc = null;
    if (isMultipart) {

      ServletFileUpload upload = new ServletFileUpload();

      upload.setSizeMax(mU);
      try {
        FileItemIterator iter = upload.getItemIterator(req);
        // List<FileItem> items = upload.parseRequest(req);

        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          // for (int ct = 0;ct < items.size();ct++){

          //         FileItem item = (FileItem)items.get(ct);

          String name = item.getName();
          // (name + " jiql UREEAD 1aay " + item.isFormField() + ":" + name.equals("directValues"));

          InputStream stream = item.openStream();
          // InputStream stream = item.getInputStream();

          //// (name + " jiql UREEAD 1 " + stream.available());
          // byte[] b = StreamUtil.readBytes(stream);

          if (name.equals("directValues")) {
            // (stream.available() + " jiql UREEAD " );

            // ByteArrayInputStream bout = new ByteArrayInputStream(b);
            ObjectInputStream dout = new ObjectInputStream(stream);

            // ObjectInputStream dout = new ObjectInputStream(bout);
            dv = (Hashtable) dout.readObject();
          }
        }

      } catch (Exception e) {
        tools.util.LogMgr.err("JS.readDV " + e.toString());
        e.printStackTrace();
      }
      // ("$$$ DV " + dv);
      Hashtable pars = (Hashtable) dv.get("parameters");
      if (pars != null) {
        Enumeration en = pars.keys();
        while (en.hasMoreElements()) {
          String n = en.nextElement().toString();
          // ("PARSMS " + n);
          if (n.equals("query")) sql = pars.get(n).toString();
          else if (n.equals("password")) password = pars.get(n).toString();
          else if (n.equals("user")) user = pars.get(n).toString();
          else if (n.equals("date.format")) dfo = pars.get(n).toString();
          else if (n.equals("encoding")) enc = pars.get(n).toString();
        }
      }
    }

    if (user == null) user = req.getParameter("user");
    if (password == null) password = req.getParameter("password");
    if (!StringUtil.isRealString(user) || !StringUtil.isRealString(password)) {
      resp.sendError(403, "Invalid User or Password");
      return;
    }

    if (!StringUtil.isRealString(theUser) || !StringUtil.isRealString(thePassword)) {
      resp.sendError(403, "Invalid User OR Password");
      return;
    }

    Connection Conn = null;
    Hashtable h = new Hashtable();
    h.put("remote", "true");
    try {
      //	NameValuePairs p = new NameValuePairs(ps);
      if (!user.equals(theUser) || !password.equals(thePassword)) {
        resp.sendError(403, "Invalid User OR Invalid Password");
        return;
      }
      // throw new ServletException("Invalid User OR Password");
      if (sql == null) sql = req.getParameter("query");
      // ( "THE SQL " + sql);
      NameValuePairs nvp = new NameValuePairs();
      if (dfo == null) dfo = req.getParameter("date.format");
      if (dfo != null) nvp.put("date.format", dfo);

      if (enc == null) enc = req.getParameter("encoding");
      if (enc != null) nvp.put("encoding", enc);

      Conn = get(nvp);

      org.jiql.jdbc.Statement Stmt = (org.jiql.jdbc.Statement) Conn.createStatement();
      Stmt.setDirectValues(dv);

      Stmt.execute(sql);
      org.jiql.jdbc.ResultSet res = (org.jiql.jdbc.ResultSet) Stmt.getResultSet();

      if (res != null) {

        if (res.getResults() != null) h.put("results", res.getResults());
        if (res.getSQLParser() != null) h.put("sqlparser", res.getSQLParser());
      } else h.put("sqlparser", Stmt.getSQLParser());

      // h.put("remote","true");
      resp.setContentType("binary/object");
      // if (enc != null)
      //	resp.setCharacterEncoding(enc);
      OutputStream fos = resp.getOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(h);
      // resp.getWriter(). ("result" + h);

    } catch (Exception ex) {
      org.jiql.util.JGUtil.olog(ex);
      ex.printStackTrace();
      tools.util.LogMgr.err("JIQLServlet " + ex.toString());
      JGException je = null;
      if (ex instanceof JGException) je = (JGException) ex;
      else je = new JGException(ex.toString());

      h.put("error", je);

      resp.setContentType("binary/object");
      OutputStream fos = resp.getOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(h);

      // throw new ServletException(ex.toString());
    } finally {
      if (Conn != null)
        try {

          Conn.close();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    // Check that we have a file upload request

    filePath = getServletContext().getRealPath(request.getServletPath());
    int path = filePath.lastIndexOf('\\');
    String path1 = filePath.substring(0, path) + "\\doc\\";
    System.out.println(path1);
    filePath = path1;
    HttpSession session1 = request.getSession();
    session1.setAttribute("url", path1);

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>");
      out.println("</body>");
      out.println("</html>");
      return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    String path2 = filePath.substring(0, path) + "\\temp\\";
    factory.setRepository(new File(path2));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
          // Get the uploaded file parameters
          String fileName = fi.getName();

          /* String fieldName = fi.getFieldName();
          String contentType = fi.getContentType();
          boolean isInMemory = fi.isInMemory();
          long sizeInBytes = fi.getSize();*/

          // Write the file

          if (fileName.lastIndexOf("\\") >= 0) {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
          } else {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
          }

          String src = path1.concat(encryptFileName(fileName));

          File f3 = new File(src);
          fi.write(f3);

          List myFileList = null;

          HttpSession session = request.getSession();
          myFileList = (List) session.getAttribute("fileList");

          if (myFileList != null) {
            myFileList.add(f3.getName());
          } else {
            myFileList = new ArrayList<String>();

            myFileList.add(f3.getName());
          }

          session.setAttribute("fileList", myFileList);
        }
      }
      out.println("</body>");
      out.println("</html>");

      /*Below code is to fetch the list of upload file name's */
      /*Begin*/
      HttpSession session = request.getSession();
      List myFileList = (List) session.getAttribute("fileList");

      Iterator itr = myFileList.iterator();

      System.out.println("Fetching file Names from session :");
      int j = 0;
      while (itr.hasNext()) {
        System.out.println(" File Name " + (++j) + " :" + itr.next());
      }

      /*Ends*/
      response.sendRedirect(request.getContextPath() + "/Admin/fileupload1.jsp");
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String imageString = "";
    String imageDivId = "";
    String focusURLDivId = "";
    String normalURLDivId = "";
    String imageWidthDivId = "";
    String imageHeightDivId = "";
    String imageLocX = "";
    String imageLocY = "";
    String newImageUpdateJSON = "";

    String imageWidgetSavePath = (String) request.getSession().getAttribute("imageWidgetSavePath");

    String fileName = "";
    request.getParameter("inputImageFile");
    String contentType = request.getContentType();
    if ((contentType.indexOf("multipart/form-data") >= 0)) {
      DiskFileItemFactory dfif = new DiskFileItemFactory();
      dfif.setSizeThreshold(maximumfilesize);
      File outputDir = new File(imageWidgetSavePath);
      if (!outputDir.exists()) {
        outputDir.mkdirs();
      }
      dfif.setRepository(new File("C:/data/"));
      ServletFileUpload upload = new ServletFileUpload(dfif);
      upload.setSizeMax(maximumfilesize);
      List<FileItem> fileItem = null;
      try {
        fileItem = upload.parseRequest(request);
      } catch (FileUploadException e) {
        e.printStackTrace();
      }
      Iterator<FileItem> i = fileItem.iterator();
      try {
        File file;
        while (i.hasNext()) {
          FileItem fi = (FileItem) i.next();

          if (fi.isFormField()) {

            if (fi.getFieldName().equals("imageDivId")) {
              imageDivId = fi.getString();
            }
            if (fi.getFieldName().equals("focusURLDivId")) {
              focusURLDivId = fi.getString();
            }
            if (fi.getFieldName().equals("normalURLDivId")) {
              normalURLDivId = fi.getString();
            }
            if (fi.getFieldName().equals("imageWidthDivId")) {
              imageWidthDivId = fi.getString();
            }
            if (fi.getFieldName().equals("imageHeightDivId")) {
              imageHeightDivId = fi.getString();
            }
            if (fi.getFieldName().equals("newImageUpdateJSON")) {
              newImageUpdateJSON = fi.getString();
            }
            if (fi.getFieldName().equals("imageLocX")) {
              imageLocX = fi.getString();
            }
            if (fi.getFieldName().equals("imageLocY")) {
              imageLocY = fi.getString();
            }
          }

          if (!fi.isFormField()) {
            fileName = fi.getName();

            if (fileName.lastIndexOf("\\") >= 0) {
              file = new File(imageWidgetSavePath + fileName.substring(fileName.lastIndexOf("\\")));
            } else {
              file =
                  new File(
                      imageWidgetSavePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
            }
            fi.write(file);
            fileName = imageWidgetSavePath + fileName;
            File f = new File(fileName);
            BufferedImage bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "png", baos);
            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(baos.toByteArray());
            imageString = imageString.replaceAll("[\\t\\n\\r]+", " ");
            baos.close();
          }
        }
      } catch (Exception ex) {
        System.out.println(ex);
      }
    }
    request.setAttribute("imageDivId", imageDivId);
    request.setAttribute("focusURLDivId", focusURLDivId);
    request.setAttribute("normalURLDivId", normalURLDivId);
    request.setAttribute("imageWidthDivId", imageWidthDivId);
    request.setAttribute("imageHeightDivId", imageHeightDivId);
    request.setAttribute("imageLocX", imageLocX);
    request.setAttribute("imageLocY", imageLocY);
    request.setAttribute("imageString", imageString);
    request.setAttribute("newImageUpdateJSON", newImageUpdateJSON);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
  }
  /**
   * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
   * multipart classes (see class description).
   *
   * @param saveDir the directory to save off the file
   * @param servletRequest the request containing the multipart
   * @throws java.io.IOException is thrown if encoding fails.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
      fac.setRepository(new File(saveDir));
    }

    ProgressMonitor monitor = null;
    // Parse the request
    try {
      ServletFileUpload upload = new ServletFileUpload(fac);
      upload.setSizeMax(maxSize);

      monitor = new ProgressMonitor();
      upload.setProgressListener(monitor);
      servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor);

      List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest));

      for (FileItem item1 : items) {
        FileItem item = item1;

        if (log.isDebugEnabled()) {
          log.debug("Found item " + item.getFieldName());
        }
        if (item.isFormField()) {
          if (log.isDebugEnabled()) {
            log.debug("Item is a normal form field");
          }
          List<String> values;
          if (params.get(item.getFieldName()) != null) {
            values = params.get(item.getFieldName());
          } else {
            values = new ArrayList<String>();
          }

          // note: see http://jira.opensymphony.com/browse/WW-633
          // basically, in some cases the charset may be null, so
          // we're just going to try to "other" method (no idea if this
          // will work)
          String charset = servletRequest.getCharacterEncoding();
          if (charset != null) {
            values.add(item.getString(charset));
          } else {
            values.add(item.getString());
          }
          params.put(item.getFieldName(), values);
        } else {
          if (log.isDebugEnabled()) {
            log.debug("Item is a file upload");
          }
          List<FileItem> values;
          if (files.get(item.getFieldName()) != null) {
            values = files.get(item.getFieldName());
          } else {
            values = new ArrayList<FileItem>();
          }

          values.add(item);
          files.put(item.getFieldName(), values);
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
      log.error(e);
      errors.add(e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
    }
  }
Example #22
0
  protected void registerSchema(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws IOException, ServletException, FileUploadException, Exception {
    // Check that we have a file upload request
    String web_service_name = null;
    String new_web_service_name = null;
    String operation_name = null;
    String schemaFilename = null;
    String relative_schemaFilename = null;
    String schemaName = null;
    String inputoutput = null;
    int software_id = 0;
    String namespace = null;
    int schema_id = 0;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    factory.setSizeThreshold(30000);
    factory.setRepository(new File(""));
    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(30000);

    // Parse the request
    List items = upload.parseRequest(request);

    Iterator iter = items.iterator();

    while (iter.hasNext()) {
      FileItem item = (FileItem) iter.next();

      if (item.isFormField()) {
        if (item.getFieldName().equals("software_id")) {
          software_id = Integer.parseInt(item.getString());
        } else if (item.getFieldName().equals("schema_name")) {
          schemaName = item.getString();
        } else if (item.getFieldName().equals("web_service_name")) {
          web_service_name = item.getString();
        } else if (item.getFieldName().equals("new_web_service_name")) {
          new_web_service_name = item.getString();
        } else if (item.getFieldName().equals("operation_name")) {
          operation_name = item.getString();
        } else if (item.getFieldName().equals("inputoutput")) {
          inputoutput = item.getString();
        }

      } else {
        relative_schemaFilename =
            new String(
                "/xsd/"
                    + software_id
                    + "_"
                    + schemaName
                    + "_"
                    + ((int) (100000 * Math.random()))
                    + ".xsd");
        schemaFilename = this.xml_rep_path + relative_schemaFilename;
        System.out.println("schemaFilename: " + schemaFilename);
        File uploadedFile = new File(schemaFilename);
        item.write(uploadedFile);
      }
    }

    VendorDBConnector vendorDBConnector = new VendorDBConnector();

    schema_id =
        vendorDBConnector.insertSchemaInfo(
            software_id,
            schemaName,
            relative_schemaFilename,
            xml_rep_path,
            new_web_service_name,
            web_service_name,
            operation_name,
            inputoutput);

    String message = "";

    if (schema_id == -1) message = "The schema has NOT been registered successfully.";
    else
      message =
          "The schema has been registered successfully. You can find the registered xsd at "
              + this.xml_rep_path
              + "/xsd for the user.name: "
              + System.getProperty("user.name");

    this.forwardToPage(
        "/vendor/succImportSchema.jsp?message=" + message + "&schema_id=" + schema_id,
        request,
        response);
  }
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String id_book = "", len = "";

    // Imposto il content type della risposta e prendo l'output
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    // La dimensione massima di ogni singolo file su system
    int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
    // Dimensione massima della request
    int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB
    // Cartella temporanea
    File cartellaTemporanea = new File("C:\\tempo");

    try {
      // Creo un factory per l'accesso al filesystem
      DiskFileItemFactory factory = new DiskFileItemFactory();

      // Setto la dimensione massima di ogni file, opzionale
      factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);
      // Setto la cartella temporanea, Opzionale
      factory.setRepository(cartellaTemporanea);

      // Istanzio la classe per l'upload
      ServletFileUpload upload = new ServletFileUpload(factory);

      // Setto la dimensione massima della request, opzionale
      upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

      // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
      // tutti i field sia di tipo file che gli altri
      List<FileItem> items = upload.parseRequest(request);

      /*
       *
       * Giro per tutti i campi inviati
       */
      for (int i = 0; i < items.size(); i++) {
        FileItem item = items.get(i);

        // Controllo se si tratta di un campo di input normale
        if (item.isFormField()) {
          // Prendo solo il nome e il valore
          String name = item.getFieldName();
          String value = item.getString();
          if (name.equals("id_book")) {
            id_book = value;
          }
          if (name.equals("len")) {
            len = value;
          }
        }
        // Se si stratta invece di un file ho varie possibilità
        else {
          // Dopo aver ripreso tutti i dati disponibili
          String fieldName = item.getFieldName();
          String fileName = item.getName();
          String contentType = item.getContentType();
          boolean isInMemory = item.isInMemory();
          long sizeInBytes = item.getSize();

          // scrivo direttamente su filesystem

          File uploadedFile =
              new File("/Users/Babol/Desktop/dVruhero/aMuseWebsite/web/userPhoto/" + fileName);
          // Solo se veramente ho inviato qualcosa
          if (item.getSize() > 0) {
            item.write(uploadedFile);
            DBconnection.EditCoverBook(fileName, Integer.parseInt(id_book));
          }
        }
      }

      // out.println("</body>");
      // out.println("</html>");

    } catch (Exception ex) {
      System.out.println("Errore: " + ex.getMessage());
    } finally {
      if (len.equals("ita")) response.sendRedirect("modify_book.jsp?id_book=" + id_book);
      else response.sendRedirect("modify_book_eng.jsp?id_book=" + id_book);
    }
  }
Example #24
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>");
      out.println("</body>");
      out.println("</html>");
      return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
          // Get the uploaded file parameters
          String fieldName = fi.getFieldName();
          String fileName = fi.getName();
          String contentType = fi.getContentType();
          boolean isInMemory = fi.isInMemory();
          long sizeInBytes = fi.getSize();
          // Write the file
          if (fileName.lastIndexOf("\\") >= 0) {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
          } else {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
          }
          fi.write(file);
          out.println("Uploaded Filename: " + fileName + "<br>");
        }
      }
      out.println("</body>");
      out.println("</html>");
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }
Example #25
0
  protected void registerService(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws IOException, ServletException, FileUploadException, Exception {
    // Check that we have a file upload request

    String service_name = null;
    String serviceFilename = null;
    String relative_serviceFilename = null;
    String service_namespace = null;
    String service_version = null;
    int sourceOfWSDL = 0; // 0: no-source , 1: wsdl from file , 2: wsdl from url
    int software_id = 0;
    int service_id = 0;
    String message = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    factory.setSizeThreshold(30000);
    factory.setRepository(new File(""));
    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(30000);

    // Parse the request
    List items = upload.parseRequest(request);

    Iterator iter = items.iterator();

    while (iter.hasNext()) {
      FileItem item = (FileItem) iter.next();

      if (item.isFormField()) {

        if (item.getFieldName().equals("software_id")) {
          software_id = Integer.parseInt(item.getString());
        } else if (item.getFieldName().equals("service_name")) {
          service_name = item.getString();
        } else if (item.getFieldName().equals("service_namespace")) {
          service_namespace = item.getString();
        } else if (item.getFieldName().equals("service_version")) {
          service_version = item.getString();
        } else if (item.getFieldName().equals("from")
            && item.getString().equalsIgnoreCase("FromUrlPath")) {
          sourceOfWSDL = 2;
        } else if (item.getFieldName().equals("from")
            && item.getString().equalsIgnoreCase("service_wsdl_fromFilePath")) {
          sourceOfWSDL = 1;
        } else if (item.getFieldName().equals("FromUrlPath") && sourceOfWSDL == 2) {

          relative_serviceFilename =
              new String(
                  "/wsdl/"
                      + software_id
                      + "_"
                      + service_name
                      + "_"
                      + ((int) (100000 * Math.random()))
                      + ".wsdl");
          serviceFilename = this.xml_rep_path + relative_serviceFilename;

          File uploadedFile = new File(serviceFilename);
          FileWriter fileWriter = new FileWriter(uploadedFile);
          URL wsdlurl = new URL(item.getString());
          BufferedReader in = new BufferedReader(new InputStreamReader(wsdlurl.openStream()));

          String inputLine;
          while ((inputLine = in.readLine()) != null) {
            fileWriter.write(inputLine + System.getProperty("line.separator"));
          }
          in.close();
          fileWriter.close();
        }
      } else if (!item.isFormField() && sourceOfWSDL == 1) {

        relative_serviceFilename =
            new String(
                "/wsdl/"
                    + software_id
                    + "_"
                    + service_name
                    + "_"
                    + ((int) (100000 * Math.random()))
                    + ".wsdl");
        serviceFilename = this.xml_rep_path + relative_serviceFilename;
        File uploadedFile = new File(serviceFilename);
        item.write(uploadedFile);
      }
    }

    VendorDBConnector vendorDBConnector = new VendorDBConnector();

    service_id =
        vendorDBConnector.insertServiceInfo(
            software_id,
            service_name,
            service_version,
            relative_serviceFilename,
            xml_rep_path,
            service_namespace);

    if (service_id == -1)
      message =
          "Service has NOT been succesfully registered. Please check that the service name and the namespace are the same with the ones in the .wsdl file.";
    else
      message =
          "Service has been succesfully registered. You can find the registered wsdl at "
              + this.xml_rep_path
              + "/wsdl for the user.name: "
              + System.getProperty("user.name");

    this.forwardToPage("/vendor/succ.jsp?message=" + message, request, response);
  }
Example #26
0
  /**
   * This method will upload files and store them under the dest_path.
   *
   * <p>File names are formed by <thread_name>_<counter>_originalFileName
   *
   * <p>The returned hashmap contains a list of name value pairs, where a value
   *
   * <p>can either be normal form input parameter or the uploaded file path.
   *
   * @param HttpServletRequest request
   * @param String dest_path upload destination path
   * @return HashMap
   */
  public static HashMap parseMultipartRequest(HttpServletRequest request, String dest_path) {

    HashMap hmfield = new HashMap();

    String threadname = Thread.currentThread().getName();

    RequestContext requestContext = new ServletRequestContext(request);

    int filemaxsize = LPropertyManager.getInt("file.upload.maxsize", 2000000);

    if (FileUpload.isMultipartContent(requestContext)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();

      factory.setRepository(new File(dest_path));

      ServletFileUpload upload = new ServletFileUpload(factory);

      upload.setSizeMax(filemaxsize);

      List items = new ArrayList();

      try {

        items = upload.parseRequest(request);

      } catch (FileUploadException e1) {

        gLogger.fatalize("LUploadUtil", e1.getMessage());
      }

      Iterator it = items.iterator();

      while (it.hasNext()) {

        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

          hmfield.put(fileItem.getFieldName(), fileItem.getString());

        } else {

          if (fileItem.getName() != null && fileItem.getSize() != 0) {

            File fullFile = new File(fileItem.getName());

            String tempfile =
                dest_path + File.separator + threadname + "_" + tick() + "_" + fullFile.getName();

            hmfield.put(fileItem.getFieldName(), tempfile);

            hmfield.put("originalfilename", fullFile.getName());

            File newFile = new File(tempfile);

            try {

              fileItem.write(newFile);

            } catch (Exception e) {

              gLogger.fatalize("LUploadUtil", e.getMessage());
            }

          } else {

            gLogger.errorLog("No file is selected or the file is empty!");
          }
        }
      }
    }

    return hmfield;
  }
  @Override
  @SuppressWarnings({"rawtypes"})
  protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
      throws ServletException, IOException {

    beforePostStart();

    final DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    factory.setRepository(new File("/tmp"));

    if (!ServletFileUpload.isMultipartContent(req)) {
      LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
      final List fileItems = upload.parseRequest(req);
      String userHash = null;
      StateToken stateToken = null;
      String typeId = null;
      String fileName = null;
      FileItem file = null;
      for (final Iterator iterator = fileItems.iterator(); iterator.hasNext(); ) {
        final FileItem item = (FileItem) iterator.next();
        if (item.isFormField()) {
          final String name = item.getFieldName();
          final String value = item.getString();
          LOG.info("name: " + name + " value: " + value);
          if (name.equals(FileConstants.HASH)) {
            userHash = value;
          }
          if (name.equals(FileConstants.TOKEN)) {
            stateToken = new StateToken(value);
          }
          if (name.equals(FileConstants.TYPE_ID)) {
            typeId = value;
          }
        } else {
          fileName = item.getName();
          LOG.info(
              "file: "
                  + fileName
                  + " fieldName: "
                  + item.getFieldName()
                  + " size: "
                  + item.getSize()
                  + " typeId: "
                  + typeId);
          file = item;
        }
      }
      createUploadedFile(userHash, stateToken, fileName, file, typeId);
      onSuccess(response);
    } catch (final FileUploadException e) {
      onFileUploadException(response);
    } catch (final Exception e) {
      onOtherException(response, e);
    }
  }
  /** The POST request.EPCUpload.java */
  protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    PrintWriter out = null;

    FileItem fileItem = null;

    try {
      String oryxBaseUrl =
          req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/oryx/";

      // Get the PrintWriter
      res.setContentType("text/plain");
      res.setCharacterEncoding("utf-8");

      out = res.getWriter();

      // No isMultipartContent => Error
      final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req);
      if (!isMultipartContent) {
        printError(out, "No Multipart Content transmitted.");
        return;
      }

      // Get the uploaded file
      final FileItemFactory factory = new DiskFileItemFactory();
      final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
      servletFileUpload.setSizeMax(-1);
      final List<?> items;

      items = servletFileUpload.parseRequest(req);
      if (items.size() != 1) {
        printError(out, "Not exactly one File.");
        return;
      }

      fileItem = (FileItem) items.get(0);

      // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd
      String amlStr = fileItem.getString("UTF-8");

      amlStr =
          amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\"");

      FileOutputStream fileout = null;
      OutputStreamWriter outwriter = null;

      try {
        fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation());
        outwriter = new OutputStreamWriter(fileout, "UTF-8");
        outwriter.write(amlStr);
        outwriter.flush();

      } finally {
        if (outwriter != null) outwriter.close();
        if (fileout != null) fileout.close();
      }

      // parse AML file
      AMLParser parser =
          new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath());
      parser.parse();
      Collection<EPC> epcs = new HashSet<EPC>();
      Iterator<String> ids = parser.getModelIds().iterator();
      while (ids.hasNext()) {
        String modelId = ids.next();
        epcs.add(parser.getEPC(modelId));
      }

      // serialize epcs to eRDF oryx format
      OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl);
      oryxSerializer.parse();

      Document outputDocument = oryxSerializer.getDocument();

      // get document as string
      String docAsString = "";

      Source source = new DOMSource(outputDocument);
      StringWriter stringWriter = new StringWriter();
      Result result = new StreamResult(stringWriter);
      TransformerFactory tfactory = TransformerFactory.newInstance();
      Transformer transformer = tfactory.newTransformer();
      transformer.transform(source, result);
      docAsString = stringWriter.getBuffer().toString();

      // write response
      out.print("" + docAsString + "");

    } catch (Exception e) {
      handleException(out, e);
    } finally {
      if (fileItem != null) {
        fileItem.delete();
      }
    }
  }
  @SuppressWarnings("unchecked")
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(4096);
      factory.setRepository(tempPathFile);
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setSizeMax(4194304);
      Map map = new HashMap();

      List<FileItem> items = upload.parseRequest(request);
      Iterator<FileItem> i = items.iterator();
      String destFilePath = null;
      String fileName = "TEMP";
      String fieldName = null;
      FileItem fi = null;
      while (i.hasNext()) {
        fi = i.next();
        fieldName = fi.getFieldName();
        log.info("fieldName:" + fi.getFieldName());
        if (fieldName.matches("serialno")) {
          fileName = fieldName;
        }
        if (fieldName.matches("ufile.*")) {
          File saveFile = new File(uploadPath, fileName);
          log.info("Saved FAX FILE to " + saveFile.getAbsolutePath());
          fi.write(saveFile);

          if (Constant.isTraFaxServerSend()) {
            destFilePath = Constant.getFaxDirectory() + "/" + map.get("serialno");
            if (map.get("fileType") != null
                && "png".equalsIgnoreCase(map.get("fileType").toString())) {
              destFilePath += ".png";
              int width = NumberUtils.toInt(map.get("width").toString());
              ImageRenderer.renderToImage(saveFile, destFilePath, width);
              map.put("filename", map.get("serialno") + ".png");
              if (MagickImageOp.isWinOS()) {
                String tiffImage = null;
                log.debug("width:" + width);
                if (width > 700) {
                  tiffImage = MagickImageOp.getInstance().buildHTiff(destFilePath);
                } else {
                  tiffImage = MagickImageOp.getInstance().buildVTiff(destFilePath);
                }
                map.put("filename", tiffImage.substring(tiffImage.lastIndexOf("/") + 1));
                new File(destFilePath).delete();
              }
              saveFile.delete();
            } else {
              destFilePath += ".xls";
              File dest = new File(destFilePath);
              saveFile.renameTo(dest);
              map.put("filename", dest.getName());
            }
            log.info("destFilePath:" + destFilePath);
            TrafaxStatusDao statusDao = (TrafaxStatusDao) ServiceContext.getBean("trafaxStatusDao");
            statusDao.addFaxOut(map);
          } else {
            FaxWriter faxWriter = new FaxWriter();
            faxWriter.write(map, saveFile);
          }
        } else {
          log.info(fi.getFieldName() + "=" + fi.getString());
          map.put(fieldName, fi.getString());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #30
0
  /** The POST request. */
  protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    // No isMultipartContent => Error
    final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req);
    if (!isMultipartContent) {
      printError(res, "No Multipart Content transmitted.");
      return;
    }

    // Get the uploaded file
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setSizeMax(-1);
    final List<?> items;
    try {
      items = servletFileUpload.parseRequest(req);
      if (items.size() != 1) {
        printError(res, "Not exactly one File.");
        return;
      }
    } catch (FileUploadException e) {
      handleException(res, e);
      return;
    }
    final FileItem fileItem = (FileItem) items.get(0);

    // Get filename and content (needed to distinguish between EPML and AML)
    final String fileName = fileItem.getName();
    String content = fileItem.getString();

    // Get the input stream
    final InputStream inputStream;
    try {
      inputStream = fileItem.getInputStream();
    } catch (IOException e) {
      handleException(res, e);
      return;
    }

    // epml2eRDF XSLT source
    final String xsltFilename = getServletContext().getRealPath("/xslt/EPML2eRDF.xslt");
    //    	final String xsltFilename = System.getProperty("catalina.home") +
    // "/webapps/oryx/xslt/EPML2eRDF.xslt";
    final File epml2eRDFxsltFile = new File(xsltFilename);
    final Source epml2eRDFxsltSource = new StreamSource(epml2eRDFxsltFile);

    // Transformer Factory
    final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    // Get the epml source
    final Source epmlSource;

    if (fileName.endsWith(".epml") || content.contains("http://www.epml.de")) {
      epmlSource = new StreamSource(inputStream);
    } else {
      printError(res, "No EPML or AML file uploaded.");
      return;
    }

    // Get the result string
    String resultString = null;
    try {
      Transformer transformer = transformerFactory.newTransformer(epml2eRDFxsltSource);
      StringWriter writer = new StringWriter();
      transformer.transform(epmlSource, new StreamResult(writer));
      resultString = writer.toString();
    } catch (Exception e) {
      handleException(res, e);
      return;
    }

    if (resultString != null) {
      try {

        printResponse(res, resultString);

      } catch (Exception e) {
        handleException(res, e);
        return;
      }
    }
  }