public HttpParams(HttpServletRequest request) throws UnsupportedEncodingException {
    // 检测是否是一个文件上传请求
    this.request = request;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setHeaderEncoding("UTF-8");
      RequestContext requestContext = new ServletRequestContext(request);
      try {
        List<FileItem> items = upload.parseRequest(requestContext);
        Iterator<FileItem> itr = items.iterator();
        avs = new HashMap<String, String>();
        fileitemMap = new HashMap<String, FileItem>();
        while (itr.hasNext()) {
          FileItem item = (FileItem) itr.next();
          String fieldName = item.getFieldName();
          if (item.isFormField()) {
            avs.put(fieldName, item.getString("UTF-8"));
          } else {
            fileitemMap.put(fieldName, item);
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    } else { // 非文件上传请求  (参数加密)
      request.setCharacterEncoding("utf-8");
      String s = request.getParameter("__");
      // s = URLDecoder.decode(s,"UTF-8");
      // logger.info("http reqeust params: "+s);
      if (s != null && !s.equals("")) {
        try {
          encoded = true;
          //					String str = DataUtil.decodeECBString(password, DataUtil.HexString2Bytes(s));
          String str = DataUtil.decodeECBString(password, DataUtil.decodeBase64(s));
          String[] pairs = str.split("&");
          params = new HashMap<String, String>();

          for (int i = 0; i < pairs.length; i++) {
            // String[] tokens = pairs[i].split("=");
            int index = pairs[i].indexOf("=");
            String key = pairs[i].substring(0, index);
            String value = pairs[i].substring(index + 1, pairs[i].length());
            params.put(key, URLDecoder.decode(value, "UTF-8"));
          }
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
예제 #2
0
  @Override
  public void execute(HttpServletRequest request) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Logger.debug("UploadImageCmd - request: " + request);
    if (!isMultipart) {
      Logger.debug("UploadImageCmd - nao multipart");
    } else {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      List<FileItem> items = null;

      try {
        items = upload.parseRequest(request);
        Logger.debug("itens: " + items);
      } catch (FileUploadException e) {
        Logger.error("Upload de imagem falhou", e);
      }
      Iterator<FileItem> itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = itr.next();
        if (item.isFormField()) {
          String name = item.getFieldName();
          String value = item.getString();
          Logger.debug("Campo de formulario: " + name + " = " + value);
        } else {
          try {
            String mimetype = item.getContentType();
            Logger.debug("Mimetype: " + mimetype);
            if (StringUtils.isEmpty(mimetype) || !mimetype.startsWith("image/")) {
              Logger.warning("Mimetype invalido.");
              continue;
            }

            // Vamos reimensionar a imagem caso necessario (para que ela nao fique muito grande)
            BufferedImage img = resizeImg(item.getInputStream());

            String itemName = item.getName();
            Random generator = new Random();
            int r = generator.nextInt(Integer.MAX_VALUE);

            String reg = "[.*]";
            String replacingtext = "";

            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(itemName);
            StringBuffer buffer = new StringBuffer();

            while (matcher.find()) {
              matcher.appendReplacement(buffer, replacingtext);
            }
            int indexOf = itemName.indexOf(".");
            String extension = itemName.substring(indexOf + 1);
            Logger.debug("extensao: " + extension);

            String finalImage = buffer.toString() + "_" + r + "." + extension;
            Logger.debug("Imagem Final === " + finalImage);

            String path = request.getServletContext().getRealPath("/pictures");
            File savedFile = new File(path + "/" + finalImage);
            ImageIO.write(img, extension, savedFile);

            mImagePath = savedFile.getAbsolutePath();
            request.setAttribute("img", "pictures/" + finalImage);
            Logger.debug("Imagem salva em: " + mImagePath);
          } catch (Exception e) {
            Logger.error("Erro no upload da imagem", e);
          }
        }
      }
    }
  }
예제 #3
0
  private void updateCover(
      HttpServletRequest request, HttpServletResponse response, final String method)
      throws FileUploadException, ServletException, IOException, IllegalAccessException,
          InvocationTargetException {
    List<String> types = Arrays.asList(".jpg", ".gif", ".png", ".jpeg"); // supported
    // type

    DiskFileItemFactory dfi = new DiskFileItemFactory(); // apache's
    // component

    dfi.setSizeThreshold(1024 * 1024); // 1M, and default is 10k, and
    // excessed will be saved in the
    // cache file
    String path = getServletContext().getRealPath("/WEB-INF/temp");
    dfi.setRepository(new File(path)); // temporary cached file

    ServletFileUpload sf = new ServletFileUpload(dfi);
    sf.setHeaderEncoding("utf-8");
    // sf.setFileSizeMax(1024*1024*5); //set single file's max size

    List<FileItem> lf = sf.parseRequest(new ServletRequestContext(request));
    Map<String, String> map = new HashMap<String, String>();
    List<String> idf = new LinkedList<String>();
    FileItem fi = null; // for stream file
    String ids[];

    for (FileItem item : lf) {
      if (item.isFormField()) { // ordinary input
        String name = item.getFieldName();
        String value = item.getString("utf-8");
        map.put(name, value);
        if ("category".equals(name)) {
          idf.add(value);
        }
        System.out.println(name + " " + value);
      } else { // stream
        String name = item.getName();
        if (name == null || "".equals(name)) {
          continue;
        }
        String ext = name.substring(name.lastIndexOf("."));
        System.out.println(ext);
        if (!types.contains(ext.toLowerCase())) {
          request.setAttribute("message", "sorryia..  i don't support type " + ext);
          return;
        }

        fi = item;
      }
    }

    Book book = new Book();
    ConvertUtils.register(new DateLocaleConverter(), Date.class);
    BeanUtils.populate(book, map);
    BookDaoImpl bdi = new BookDaoImpl();
    ids = new String[idf.size()];
    idf.toArray(ids);
    int id;

    if (method.equals(BOOK_ADD)) {
      id = bdi.add(book, ids);
      request.setAttribute("message", "add book successfully...");
    } else {
      id = Integer.parseInt(map.get("id"));
      book.setId(id);
      bdi.update(book);
      bdi.updateCategory(id, ids);
      request.setAttribute("message", "update book successfully...");
    }

    if (fi != null) { // upload file
      InputStream is = fi.getInputStream();
      String Spath = getServletContext().getRealPath("/img/bookcover/");
      System.out.println(Spath);
      FileOutputStream fos = new FileOutputStream(new File(Spath + id + ".jpg"));
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = is.read(b)) > 0) {
        fos.write(b, 0, len);
      }
      fos.close();
      is.close();
      fi.delete(); // the temporary file would be deleted.
    }
  }
예제 #4
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    logger.info("post: " + req.getQueryString());

    String sessionId = req.getParameter("sessionId");
    if (!Utils.isNullOrEmpty(sessionId)) {
      Session session = getSessionCache().getSessionForSessionId(sessionId);
      if (session.getUserProfile() != null) {
        String uploadType = req.getParameter("upload");
        logger.info("got uploadrequest, type: " + uploadType);
        String response = "success";
        String callbackName = "";
        try {
          // Create a factory for disk-based file items
          FileItemFactory factory = new DiskFileItemFactory();

          // Create a new file upload handler
          ServletFileUpload upload = new ServletFileUpload(factory);
          upload.setSizeMax(1024 * 1024);
          upload.setFileSizeMax(1024 * 1024 * 500);
          // Parse the request
          List<FileItem> /* FileItem */ items = upload.parseRequest(req);

          Iterator<FileItem> iter = items.iterator();
          while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
              logger.info("formfield " + item.getFieldName());
              if ("callbackName".equals(item.getFieldName())) callbackName = item.getString();
            } else {
              logger.info("filefield " + item.getFieldName());
              if ("userPicture".equals(uploadType)) {
                logger.info("Setting new user picture for " + session.getUserProfile());

                UserCredentials userCredentials = session.getUserProfile().getUserCredentials();
                // creating the small image
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                scalePictureToMax(new ByteArrayInputStream(item.get()), bo, 50, 50);
                userCredentials.setSmallPicture(bo.toByteArray());
                // creating big picture
                bo = new ByteArrayOutputStream();
                scalePictureToMax(new ByteArrayInputStream(item.get()), bo, 500, 500);
                userCredentials.setPicture(bo.toByteArray());

                session.getUserProfile().setUserCredentials(userCredentials);
              }
            }
          }

        } catch (Exception e) {
          logger.error("error sending user picture", e);
          response = "Error, for details see the server log files.";
        }

        logger.info("Callback name: " + callbackName);
        resp.getWriter()
            .print(
                "<script type=\"text/javascript\">window.top."
                    + callbackName
                    + "('"
                    + response
                    + "');</script>");
      }
    } else super.doPost(req, resp);
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    String message = "File upload.";
    List<String> filenames = null;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    HttpSession session = request.getSession(false);
    User loggedUser = null;
    if (session != null) loggedUser = (User) session.getAttribute("loggedUser");
    if (loggedUser == null) {
      request.getRequestDispatcher("login.jsp").forward(request, response);
    } else {
      Book book = new Book();
      if (isMultipart) {
        ServletContext context = this.getServletConfig().getServletContext();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        File repoPath = (File) context.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repoPath);

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

        try {
          List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));
          filePath = request.getServletContext().getRealPath("/") + "picture/";
          filenames = new ArrayList<String>();

          for (FileItem fi : fileItems) {
            if (!fi.isFormField()) {
              // Get the uploaded file parameters
              String fieldName = fi.getFieldName();
              if (fi.getName() != null && !fi.getName().equals("")) {
                String fileName = URLEncoder.encode(fi.getName(), "UTF-8");

                String contentType = fi.getContentType();

                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                file = new File(filePath + fileName);
                fi.write(file);
                book.setPictureURL("picture/" + fileName);
              }
            } else {
              String fieldName = fi.getFieldName();
              String fieldValue = fi.getString();
              if (fieldName.equals("title")) {
                if (fieldValue != null) {
                  book.setTitle(fieldValue);
                  ;
                }
              }
              if (fieldName.equals("authors")) book.setAuthors(fieldValue);
              if (fieldName.equals("publisher")) book.setPublisher(fieldValue);
              if (fieldName.equals("description"))
                if (fieldValue != null) {
                  book.setDescription(fieldValue);
                }
              if (fieldName.equals("genre")) book.setGenre(fieldValue);
              if (fieldName.equals("numberInStock"))
                book.setNumberInStock(Integer.parseInt(fieldValue));
              if (fieldName.equals("publicationYear"))
                book.setPublicationYear(Integer.parseInt(fieldValue));
              if (fieldName.equals("price")) book.setPrice(Double.parseDouble(fieldValue));
            }
          }
        } catch (Exception ex) {
          System.out.println(ex);
        }
      }

      BookDAO bookDao = new BookDAO();
      bookDao.add(book);

      response.sendRedirect("LoginBookPreviewViewController");
    }
  }
예제 #6
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();

    String idx = request.getParameter("idx");

    // 获得磁盘文件条目工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 获取文件需要上传到的路径
    String rootPath = getServletContext().getRealPath("/upload");

    // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
    // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
    /** 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的 然后再将其真正写到 对应目录的硬盘上 */
    File uploadDir = new File(rootPath);
    if (!uploadDir.exists()) {
      uploadDir.mkdirs();
    }
    factory.setRepository(uploadDir);
    // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
    factory.setSizeThreshold(1024 * 1024);

    boolean isUpload = ServletFileUpload.isMultipartContent(request);
    // 高水平的API文件上传处理
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
      // 可以上传多个文件
      List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

      for (FileItem item : list) {
        // 获取表单的属性名字
        String fileName = item.getName();

        // 如果获取的 表单信息是普通的 文本 信息
        if (item.isFormField()) {
        }
        // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
        else {

          String md5Name = MD5Code.getInstance().getCode(fileName + System.currentTimeMillis());
          String fiffux = fileName.substring(fileName.lastIndexOf("."));

          // 真正写到磁盘上
          // 它抛出的异常 用exception 捕捉
          File f = new File(rootPath + File.separatorChar, md5Name + fiffux);

          if (!f.exists()) {
            f.createNewFile();
          }
          item.write(f); // 第三方提供的

          JSONObject result = new JSONObject();
          JSONObject payload = new JSONObject();

          responseJavaScript(
              out, "parent.uploadImageComplete('" + idx + "','" + (md5Name + fiffux) + "')");

          out.close();
        }
      }

    } catch (FileUploadException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }