@SuppressWarnings("unchecked")
  private void parseParams(HttpServletRequest req) {
    try {
      Map m = req.getParameterMap();
      for (Object e0 : m.entrySet()) {
        Map.Entry<String, ?> e = (Map.Entry<String, ?>) e0;
        Object v = e.getValue();
        String vs =
            v instanceof String[]
                ? StringUtils.join((String[]) v, "")
                : ObjectUtils.toString(v, "");
        setString(e.getKey(), vs);
      }

      if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = createFileUpload();
        List<FileItem> fileItems = upload.parseRequest(req);
        for (FileItem fileItem : fileItems) {
          if (fileItem.isFormField()) {
            setString(fileItem.getFieldName(), fileItem.getString(Charsets.DEFAULT));
          } else {
            put(fileItem.getFieldName(), fileItem);
          }
        }
      }
    } catch (Exception e) {
      throw new WebException(e);
    }
  }
Esempio n. 2
0
	public boolean isMultipart(HttpServletRequest request) {
		String contenttype = request.getContentType();
		if (request == null) {
			return false;
		}
		else if(contenttype != null && contenttype.equals(MultipartResolver.mimetype_application_octet_stream))
		{
			return true;
		}
		else if (commonsFileUpload12Present) {
			return ServletFileUpload.isMultipartContent(request);
		}
		else {
			return ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
		}
	}
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Fachada fachada = Fachada.obterInstancia();
    String acao = "";
    List<FileItem> items = null;
    if (ServletFileUpload.isMultipartContent(request)) {

      try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
      } catch (FileUploadException e1) {

        e1.printStackTrace();
      }

      for (FileItem item : items) {
        if (item.getFieldName().equals("acao")) {
          acao = item.getString();
        }
      }
    } else {
      acao = request.getParameter("acao");
    }

    try {
      if (acao.equals("deletar")) {
        deletarMembro(request, fachada);
      } else {
        cadastrarEditarMembro(request, response, fachada, acao, items);
      }
      request.getRequestDispatcher("sucesso.jsp").forward(request, response);
    } catch (Exception e) {
      e.printStackTrace();
      request.getRequestDispatcher("falha.jsp").forward(request, response);
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    super.doPost(request, response);

    try {
      if (!ServletFileUpload.isMultipartContent(request)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }

      ServletFileUpload sfU = new ServletFileUpload();
      FileItemIterator items = sfU.getItemIterator(request);
      while (items.hasNext()) {
        FileItemStream item = items.next();
        if (!item.isFormField()) {
          InputStream stream = item.openStream();
          Document doc = editor.toDocument(stream);
          stream.close();
          handleDocument(request, response, doc);
          return;
        }
      }

      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded");
    } catch (FileUploadException fuE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage());
    } catch (JDOMException jE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage());
    }
  }
  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);
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String id = request.getParameter("id");
    String firstname = request.getParameter("firstname");
    String lastname = request.getParameter("lastname");
    String phone = request.getParameter("phone");
    String email = request.getParameter("email");
    String attendance = request.getParameter("attendance");
    String photo = request.getParameter("upload");
    String insert = request.getParameter("insert");

    StudDao sd = new StudDao();
    List<Student> list = sd.select();
    request.setAttribute("List", list);

    if (ServletFileUpload.isMultipartContent(request)) {
      //   System.out.println("file Uploading");

      RequestDispatcher rd = request.getRequestDispatcher("/StudentUpload");
      rd.forward(request, response);
    }

    if (insert != null && insert != "") {

      sd.insert(firstname, lastname, email, attendance, photo, phone, Integer.parseInt("enroll"));
      list = sd.select();
      request.setAttribute("List", list);

      response.sendRedirect("Student/form");
    }
  }
Esempio n. 7
0
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
   if (!ServletFileUpload.isMultipartContent(request)) {
     response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
     return;
   }
   try {
     List<FileItem> files = uploadHandler.parseRequest(request);
     if (files.size() == 0) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     FileItem fileItem = files.get(0);
     if (!fileItem.getContentType().equals(Constants.CLASS_CONTENT_TYPE)
         || fileItem.isFormField()) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     String folderName =
         baseDir + request.getRequestURI().replaceAll("/", Constants.FILE_SEPARATOR);
     File folder = new File(folderName);
     if (folder.exists() && !folder.isDirectory()) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     if (!folder.exists()) {
       folder.mkdirs();
     }
     fileItem.write(new File(folderName + Constants.FILE_SEPARATOR + fileItem.getName()));
   } catch (Exception e) {
     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     return;
   }
 }
Esempio n. 8
0
  private void parseRequest(
      HttpServletRequest request, Map<String, String> parameters, List<file> files)
      throws IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
      List<FileItem> fileItems = parseMultipartRequest(request);

      long fileSizeMaxMB = ServerConfig.webServerUploadMax();
      long fileSizeMax = fileSizeMaxMB > 0 ? fileSizeMaxMB * NumericUtils.Megabyte : Long.MAX_VALUE;

      for (FileItem fileItem : fileItems) {
        if (!fileItem.isFormField()) {
          if (fileItem.getSize() > fileSizeMax)
            throw new RuntimeException(
                Resources.format(
                    "Exception.fileSizeLimitExceeded", fileItem.getName(), fileSizeMaxMB));
          files.add(new file(fileItem));
        } else
          parameters.put(fileItem.getFieldName(), fileItem.getString(encoding.Default.toString()));
      }
    } else {
      @SuppressWarnings("unchecked")
      Map<String, String[]> requestParameters = request.getParameterMap();

      for (String name : requestParameters.keySet()) {
        String[] values = requestParameters.get(name);
        parameters.put(name, values.length != 0 ? values[0] : null);
      }
    }

    parameters.put(Json.ip.get(), request.getRemoteAddr());
  }
 @RequestMapping(value = "/UploadFile.htm")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   File file = null;
   try {
     List<FileItem> items = upload.parseRequest(request);
     if (isMultipart) {
       for (FileItem item : items) {
         if (!item.isFormField()) {
           String name = new File(item.getName()).getName();
           file = new File(request.getRealPath(File.separator) + File.separator + name);
           item.write(file);
         }
       }
       readFileImpl.readCSVFile(file);
       request.getRequestDispatcher("jsp/display.jsp").forward(request, response);
     }
   } catch (FileUploadException e) {
     e.printStackTrace();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Esempio n. 10
0
 /**
  * Start the Upload of the items
  *
  * @throws Exception
  */
 public void upload() throws Exception {
   UserController uc = new UserController(null);
   user = uc.retrieve(getUser().getEmail());
   HttpServletRequest req =
       (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
   boolean isMultipart = ServletFileUpload.isMultipartContent(req);
   if (isMultipart) {
     ServletFileUpload upload = new ServletFileUpload();
     // Parse the request
     FileItemIterator iter = upload.getItemIterator(req);
     while (iter.hasNext()) {
       FileItemStream fis = iter.next();
       InputStream stream = fis.openStream();
       if (!fis.isFormField()) {
         title = fis.getName();
         File tmp = createTmpFile();
         try {
           writeInTmpFile(tmp, stream);
           Item item = uploadFile(tmp);
           if (item != null) itemList.add(item);
         } finally {
           stream.close();
           FileUtils.deleteQuietly(tmp);
         }
       }
     }
   }
 }
Esempio n. 11
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");
   }
 }
Esempio n. 12
0
  void restUploadWordlist(final PwmRequest pwmRequest)
      throws IOException, ServletException, PwmUnrecoverableException {

    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    if (!ServletFileUpload.isMultipartContent(req)) {
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, "no file found in upload");
      pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
      LOGGER.error(pwmRequest, "error during import: " + errorInformation.toDebugStr());
      return;
    }

    final InputStream inputStream =
        ServletHelper.readFileUpload(pwmRequest.getHttpServletRequest(), "uploadFile");
    try {
      pwmApplication.getWordlistManager().populate(inputStream);
    } catch (PwmUnrecoverableException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
      final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest);
      LOGGER.debug(pwmRequest, errorInfo.toDebugStr());
      pwmRequest.outputJsonResult(restResultBean);
      return;
    }

    pwmRequest.outputJsonResult(
        RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown));
  }
Esempio n. 13
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);
    }
  }
Esempio n. 14
0
  @Override
  public void execute(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    ResourceBundle bundle = (ResourceBundle) session.getAttribute("bundle");

    String jsonError = "";
    ServletContext context = request.getSession().getServletContext();
    response.setContentType("application/json");

    try {
      if (ServletFileUpload.isMultipartContent(request)) {
        String fileName;
        String filePath;
        FileType.Type type;
        List<FileItem> multiparts =
            new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : multiparts) {
          if (!item.isFormField()) {
            fileName = new File(item.getName()).getName();
            type = FileType.getType(fileName);
            if (type != null) {
              filePath = context.getRealPath(type.getPath());
              SecureRandom random = new SecureRandom();
              fileName =
                  new BigInteger(130, random).toString(32) + FileType.parseFileFormat(fileName);
              item.write(new File(filePath + File.separator + fileName));
              request
                  .getSession()
                  .setAttribute(
                      "urlCat",
                      ServerLocationUtils.getServerPath(request) + type.getPath() + "/" + fileName);
              LOG.debug("File uploaded successfully");
              response
                  .getWriter()
                  .print(
                      new JSONObject()
                          .put(
                              "success",
                              UTF8.encoding(bundle.getString("notification.upload.file.success"))));
            } else {
              jsonError = UTF8.encoding(bundle.getString("notification.wrong.file.format"));
            }
          }
        }
      } else {
        jsonError = UTF8.encoding(bundle.getString("notification.request.error"));
      }
    } catch (Exception e) {
      LOG.error(e.getLocalizedMessage(), e);
      jsonError = UTF8.encoding(bundle.getString("notification.upload.file.error"));
    } finally {
      if (!jsonError.isEmpty()) {
        response.getWriter().print(new JSONObject().put("error", jsonError));
      }
    }
  }
  /**
   * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse response)
      throws ServletException, IOException {
    // Extract the relevant content from the POST'd form
    if (ServletFileUpload.isMultipartContent(req)) {
      Map<String, String> responseMap;
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);

      // Parse the request
      String deploymentType = null;
      String version = null;
      String fileName = null;
      InputStream artifactContent = null;
      try {
        List<FileItem> items = upload.parseRequest(req);
        for (FileItem item : items) {
          if (item.isFormField()) {
            if (item.getFieldName().equals("deploymentType")) { // $NON-NLS-1$
              deploymentType = item.getString();
            } else if (item.getFieldName().equals("version")) { // $NON-NLS-1$
              version = item.getString();
            }
          } else {
            fileName = item.getName();
            if (fileName != null) fileName = FilenameUtils.getName(fileName);
            artifactContent = item.getInputStream();
          }
        }

        // Default version is 1.0
        if (version == null || version.trim().length() == 0) {
          version = "1.0"; // $NON-NLS-1$
        }

        // Now that the content has been extracted, process it (upload the artifact to the s-ramp
        // repo).
        responseMap = uploadArtifact(deploymentType, fileName, version, artifactContent);
      } catch (SrampAtomException e) {
        responseMap = new HashMap<String, String>();
        responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$
        responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$
        responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$
      } catch (Throwable e) {
        responseMap = new HashMap<String, String>();
        responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$
        responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$
        responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$
      } finally {
        IOUtils.closeQuietly(artifactContent);
      }
      writeToResponse(responseMap, response);
    } else {
      response.sendError(
          HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
          Messages.i18n.format("DeploymentUploadServlet.ContentTypeInvalid")); // $NON-NLS-1$
    }
  }
Esempio n. 16
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      ArrayList<String> array = new ArrayList<>();
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      if (isMultipart) {
        FileItemFactory fit = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fit);
        File savePath = null;
        try {
          List<FileItem> ft = upload.parseRequest(request);
          for (FileItem f : ft) {
            if (!f.isFormField()) {
              String n = new File(f.getName()).getName();
              savePath =
                  new File(
                      request.getServletContext().getRealPath("/")
                          + "images/"
                          + System.currentTimeMillis()
                          + "_"
                          + n);
              f.write(savePath);
              array.add(savePath.getName());
            }
            /** file upload ends */

            /** Start Get data from <inputs> */
            if (f.isFormField()) {
              String value = f.getString();
              array.add(value);
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (array.get(0).toString().equals("addHotelPic")) {
        model.pojo.HotelPictures hotel_pictures = new model.pojo.HotelPictures();
        model.pojo.ActionStatus action_status =
            (model.pojo.ActionStatus)
                model.DbManager.getInstance().retrieveDataById(model.pojo.ActionStatus.class, 6);
        model.pojo.Hotel hotel =
            (model.pojo.Hotel)
                model.DbManager.getInstance()
                    .retrieveDataById(model.pojo.Hotel.class, Integer.parseInt(array.get(1)));

        hotel_pictures.setActionStatus(action_status);
        hotel_pictures.setHotel(hotel);
        hotel_pictures.setUrl(array.get(2).toString());

        model.DbManager.getInstance().saveData(hotel_pictures);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 17
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!");
    }
  }
Esempio n. 18
0
  /**
   * Takes in a photo from a form, scales it to have at least the IMAGE_WIDTH and IMAGE_HEIGHT, and
   * outputs it to the browser
   *
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   * @return Outputs the URL stripped of it's path of the photo that is at least IMAGE_WIDTH by
   *     IMAGE_HEIGHT.
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);

    // Only process the servlet if the form contains an image
    if (isMultiPart) {
      uploadPhoto(request, response);
    }
  }
Esempio n. 19
0
  public void processUpload(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    String hasHotDeployment =
        (String) configContext.getAxisConfiguration().getParameterValue("hotdeployment");
    String hasHotUpdate =
        (String) configContext.getAxisConfiguration().getParameterValue("hotupdate");
    req.setAttribute("hotDeployment", (hasHotDeployment.equals("true")) ? "enabled" : "disabled");
    req.setAttribute("hotUpdate", (hasHotUpdate.equals("true")) ? "enabled" : "disabled");
    RequestContext reqContext = new ServletRequestContext(req);

    boolean isMultipart = ServletFileUpload.isMultipartContent(reqContext);
    if (isMultipart) {

      try {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<?> items = upload.parseRequest(req);
        // Process the uploaded items
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
          FileItem item = (FileItem) iter.next();
          if (!item.isFormField()) {

            String fileName = item.getName();
            String fileExtesion = fileName;
            fileExtesion = fileExtesion.toLowerCase();
            if (!(fileExtesion.endsWith(".jar") || fileExtesion.endsWith(".aar"))) {
              req.setAttribute("status", "failure");
              req.setAttribute("cause", "Unsupported file type " + fileExtesion);
            } else {

              String fileNameOnly;
              if (fileName.indexOf("\\") < 0) {
                fileNameOnly = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
              } else {
                fileNameOnly =
                    fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
              }

              File uploadedFile = new File(serviceDir, fileNameOnly);
              item.write(uploadedFile);
              req.setAttribute("status", "success");
              req.setAttribute("filename", fileNameOnly);
            }
          }
        }
      } catch (Exception e) {
        req.setAttribute("status", "failure");
        req.setAttribute("cause", e.getMessage());
      }
    }
    renderView("upload.jsp", req, res);
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse resp)
      throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter;
    try {
      iter = upload.getItemIterator(request);

      while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
          System.out.println(
              "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
        } else {
          System.out.println(
              "File field " + name + " with file name " + item.getName() + " detected.");
          // Process the input stream
          int read = 0;
          final byte[] bytes = new byte[1024];
          FileOutputStream fileOut = new FileOutputStream(new File(item.getName()));
          while ((read = stream.read(bytes)) != -1) {
            System.out.println("read " + read + " bytes");
            fileOut.write(bytes, 0, read);
          }
          stream.close();
          fileOut.close();
        }
      }
    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //		final Part filePart = req.getPart("file");
    //	    int read = 0;
    //        final byte[] bytes = new byte[1024];
    //        InputStream filecontent = filePart.getInputStream();
    //	    final String fileName = getFileName(filePart);
    //        FileOutputStream fileOut = new FileOutputStream(new File(fileName));
    //        while ((read = filecontent.read(bytes)) != -1) {
    //            System.out.println("read " + read + " bytes");
    //            fileOut.write(bytes, 0, read);
    //        }
    //        filecontent.close();
    //        fileOut.close();

  }
Esempio n. 21
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (ServletFileUpload.isMultipartContent(request)) {
      UploadTools uploadTools = new UploadTools();
      String path = request.getSession().getServletContext().getRealPath("/") + "/";
      ServletFileUpload upload = uploadTools.initUpload(path);
      String image = null, introduce = null, strategy = null;
      try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
          FileItem item = iter.next();

          if ("introduce".equals(item.getFieldName())) {
            introduce = item.getString(request.getCharacterEncoding());
          } else if ("strategy".equals(item.getFieldName())) {
            strategy = item.getString(request.getCharacterEncoding());
          } else {
            image = uploadTools.uploadFile(path, item);
            System.out.println(image);
          }
        }
      } catch (FileUploadException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

      HttpSession session = request.getSession(true);
      Object cityName = session.getAttribute("searchcity");
      // System.out.println(cityName);
      // Object image1 = session.getAttribute("image");

      DBTools dbtools = new DBTools();
      String sql =
          "update city set c_introduce='"
              + introduce
              + "',c_path='"
              + image
              + "',c_strategy='"
              + strategy
              + "' where c_name='"
              + cityName
              + "';";

      int count = dbtools.update(sql);
      if (count > 0) {
        response.sendRedirect("success.jsp");
      }
    }
  }
  /**
   * Parse request parameters and files.
   *
   * @param request
   * @param response
   */
  protected void parseRequest(HttpServletRequest request, HttpServletResponse response) {
    requestParams = new HashMap<String, Object>();
    listFiles = new ArrayList<FileItemStream>();
    listFileStreams = new ArrayList<ByteArrayOutputStream>();

    // Parse the request
    if (ServletFileUpload.isMultipartContent(request)) {
      // multipart request
      try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          String name = item.getFieldName();
          InputStream stream = item.openStream();
          if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream));
          } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
              listFiles.add(item);

              ByteArrayOutputStream os = new ByteArrayOutputStream();
              IOUtils.copy(stream, os);
              listFileStreams.add(os);
            }
          }
        }
      } catch (Exception e) {
        logger.error("Unexpected error parsing multipart content", e);
      }
    } else {
      // not a multipart
      for (Object mapKey : request.getParameterMap().keySet()) {
        String mapKeyString = (String) mapKey;

        if (mapKeyString.endsWith("[]")) {
          // multiple values
          String values[] = request.getParameterValues(mapKeyString);
          List<String> listeValues = new ArrayList<String>();
          for (String value : values) {
            listeValues.add(value);
          }
          requestParams.put(mapKeyString, listeValues);
        } else {
          // single value
          String value = request.getParameter(mapKeyString);
          requestParams.put(mapKeyString, value);
        }
      }
    }
  }
Esempio n. 23
0
  @Override
  public Template handleRequest(
      HttpServletRequest request, HttpServletResponse response, Context context) {

    // process only if its multipart content
    context.put("apptitle", "E-com Journal");
    String TemplateTitle = null;

    System.out.println("UPLOAD SERVLET Template title :" + TemplateTitle);
    Template template = null;
    try {

      HttpSession session = request.getSession();
      String UserRole = (String) session.getAttribute("userRole");
      System.out.println(UserRole);
      String name = null;
      if (UserRole == "Editor") {

        if (ServletFileUpload.isMultipartContent(request)) {
          try {
            List<FileItem> multiparts =
                new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
              if (!item.isFormField()) {
                name = new File(item.getName()).getName();
                item.write(new File(UPLOAD_DIRECTORY + name));
                System.out.println("name: of file:" + name);
              } else {
                TemplateTitle = item.getString();
              }
            }
            UploadModel uc = new UploadModel();
            uc.setFilePath(UPLOAD_DIRECTORY + name, TemplateTitle);
            // File uploaded successfully
            context.put("message", "File Uploaded Successfully");
            System.out.println("File Uploaded Successfully");

          } catch (Exception ex) {
            context.put("message", "File Upload Failed due to " + ex);
            System.out.println("File Upload Failed due to ");
          }
        }
      }
      template = getTemplate("/forms/upload.vm");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return template;
  }
Esempio n. 24
0
  public static void restUploadConfig(final PwmRequest pwmRequest)
      throws PwmUnrecoverableException, IOException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    if (pwmApplication.getApplicationMode() == PwmApplication.MODE.RUNNING) {
      final String errorMsg = "config upload is not permitted when in running mode";
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, errorMsg, new String[] {errorMsg});
      pwmRequest.respondWithError(errorInformation, true);
      return;
    }

    if (ServletFileUpload.isMultipartContent(req)) {
      final InputStream uploadedFile = ServletHelper.readFileUpload(req, "uploadFile");
      if (uploadedFile != null) {
        try {
          final StoredConfigurationImpl storedConfig =
              StoredConfigurationImpl.fromXml(uploadedFile);
          final List<String> configErrors = storedConfig.validateValues();
          if (configErrors != null && !configErrors.isEmpty()) {
            throw new PwmOperationalException(
                new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, configErrors.get(0)));
          }
          writeConfig(ContextManager.getContextManager(req.getSession()), storedConfig);
          LOGGER.trace(pwmSession, "read config from file: " + storedConfig.toString());
          final RestResultBean restResultBean = new RestResultBean();
          restResultBean.setSuccessMessage("read message");
          pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
          req.getSession().invalidate();
        } catch (PwmException e) {
          final RestResultBean restResultBean =
              RestResultBean.fromError(e.getErrorInformation(), pwmRequest);
          pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
          LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
        }
      } else {
        final ErrorInformation errorInformation =
            new ErrorInformation(
                PwmError.CONFIG_UPLOAD_FAILURE,
                "error reading config file: no file present in upload");
        final RestResultBean restResultBean =
            RestResultBean.fromError(errorInformation, pwmRequest);
        pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
        LOGGER.error(pwmSession, errorInformation.toDebugStr());
      }
    }
  }
Esempio n. 25
0
 /**
  * Performs an HTTP POST request
  *
  * @param httpServletRequest The {@link HttpServletRequest} object passed in by the servlet engine
  *     representing the client request to be proxied
  * @param httpServletResponse The {@link HttpServletResponse} object by which we can send a
  *     proxied response to the client
  */
 public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
     throws IOException, ServletException {
   // Create a standard POST request
   PostMethod postMethodProxyRequest = new PostMethod(this.getProxyURL(httpServletRequest));
   // Forward the request headers
   setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
   // Check if this is a mulitpart (file upload) POST
   if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
     this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
   } else {
     this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
   }
   // Execute the proxy request
   this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
 }
Esempio n. 26
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;
 }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext = getServletContext();
    UPLOAD_DIRECTORY = servletContext.getRealPath(File.separator) + "uploadedFiles";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHms");
    String name = null;
    User userModel = (User) request.getSession(false).getAttribute("user");
    String user = userModel.getUsername();
    String datePart = sdf.format(Calendar.getInstance().getTime());
    System.out.println("doPost");
    System.out.println("User : "******"isMultipartContent");
      try {
        List<FileItem> multiparts =
            new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        System.out.println("multiparts size : " + multiparts.size());
        for (FileItem item : multiparts) {
          System.out.println("isFormField: " + item.isFormField());
          if (!item.isFormField()) {
            name = new File(item.getName()).getName() + datePart;
            System.out.println("filename : " + name);
            System.out.println("UPLOAD_DIRECTORY : " + UPLOAD_DIRECTORY);
            item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
          }
        }
        // start import to DB
        message = "File Saved as filename " + name + "\n";
        save(UPLOAD_DIRECTORY + File.separator + name, user);
        // File uploaded successfully
        request.setAttribute("message", message.trim());
      } catch (Exception ex) {
        request.setAttribute("message", "File Upload Failed due to " + ex);
      }

    } else {
      request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request
        .getRequestDispatcher("./agit/bank_statement_upload_result.jsp")
        .forward(request, response);
    // response.sendRedirect("./agit/bank_statement_upload_result.jsp");

  }
Esempio n. 28
0
  private String getFile(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // 如果是文件上传类型
    StringBuffer fileStr = new StringBuffer();
    //		PrintWriter out = resp.getWriter();
    if (ServletFileUpload.isMultipartContent(req)) {
      // 得到文件上传工厂
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(5000 * 1024);
      factory.setRepository(new File("c:/temp"));

      // 处理文件上传核心类
      ServletFileUpload fileUpload = new ServletFileUpload(factory);
      fileUpload.setFileSizeMax(50000 * 1024);
      // 设置文件上传类的编码格式
      fileUpload.setHeaderEncoding("UTF-8");
      // 集合数据 : FileItem对象 注意: 每一个表单域 对应一个 FileItem对象(封装)

      try {
        List<FileItem> fileItemList = fileUpload.parseRequest(req);
        for (FileItem item : fileItemList) {
          // 如果这个文本域是文件类型的
          if (!item.isFormField()) {
            CustomLog.info(item.getFieldName());
            InputStream inputStream = item.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);

            int tempbyte;
            while ((tempbyte = bis.read()) != -1) {
              char c = (char) tempbyte;
              System.out.write(tempbyte);
              fileStr.append(c);
            }

          } else {
            //                           CustomLog.info(item.getFieldName());
            //                           CustomLog.info(item.getString());
          }
        }
      } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return fileStr.toString();
  }
Esempio n. 29
0
  public void upload() throws Exception {
    boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
    if (!isMultipart) {
      this.state = this.errorInfo.get("NOFILE");
      return;
    }

    if (this.inputStream == null) {
      this.state = this.errorInfo.get("FILE");
      return;
    }

    // 存储title
    this.title = this.getParameter("pictitle");

    try {
      String savePath = this.getFolder(this.savePath);

      if (!this.checkFileType(this.originalName)) {
        this.state = this.errorInfo.get("TYPE");
        return;
      }

      this.fileName = this.getName(this.originalName);
      this.type = this.getFileExt(this.fileName);
      this.url = savePath + "/" + this.fileName;

      FileOutputStream fos = new FileOutputStream(this.getPhysicalPath(this.url));
      BufferedInputStream bis = new BufferedInputStream(this.inputStream);
      byte[] buff = new byte[128];
      int count = -1;

      while ((count = bis.read(buff)) != -1) {

        fos.write(buff, 0, count);
      }

      bis.close();
      fos.close();

      this.state = this.errorInfo.get("SUCCESS");
    } catch (Exception e) {
      e.printStackTrace();
      this.state = this.errorInfo.get("IO");
    }
  }
  private void installBundle(HttpServletRequest request, PluginContext pluginContext) {
    if (ServletFileUpload.isMultipartContent(request)) {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);

      try {
        List<?> files = upload.parseRequest(request);

        byte[] buffer = new byte[8192];
        for (Object name : files) {
          FileItem element = (FileItem) name;

          if (!element.isFormField()) {
            String fileName = element.getName();
            if (!fileName.endsWith(".jar")) {
              throw new FileUploadException("Wrong data type. Needs to be a \".jar\".");
            }
            fileName = fileName.replace('\\', '/'); // Windows stub
            if (fileName.contains("/")) {
              fileName = fileName.substring('/' + 1);
            }

            InputStream is = element.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File("bundle", fileName));

            int len = 0;
            while ((len = is.read(buffer)) > 0) {
              fos.write(buffer, 0, len);
            }

            fos.flush();
            fos.close();
            is.close();

            context.installBundle("file:bundle/" + fileName);

            message = "Info: Installed Bundle " + fileName;
          }
        }
      } catch (Exception e) {
        message = "Error: " + e.getMessage();
      }
    }
  }