Ejemplo n.º 1
0
 /**
  * Get an uploaded file item.
  *
  * @param request
  * @param response
  * @throws IOException
  */
 public void getUploadedFile(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   String parameter = request.getParameter(PARAM_SHOW);
   FileItem item = findFileItem(getSessionFileItems(request), parameter);
   if (item != null) {
     logger.debug(
         "UPLOAD-SERVLET ("
             + request.getSession().getId()
             + ") getUploadedFile: "
             + parameter
             + " returning: "
             + item.getContentType()
             + ", "
             + item.getName()
             + ", "
             + item.getSize()
             + " bytes");
     response.setContentType(item.getContentType());
     copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream());
   } else {
     logger.info(
         "UPLOAD-SERVLET ("
             + request.getSession().getId()
             + ") getUploadedFile: "
             + parameter
             + " file isn't in session.");
     renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
   }
 }
Ejemplo n.º 2
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());
  }
Ejemplo n.º 3
0
  /**
   * Delete an uploaded file.
   *
   * @param request
   * @param response
   * @return FileItem
   * @throws IOException
   */
  protected static FileItem removeUploadedFile(
      HttpServletRequest request, HttpServletResponse response) throws IOException {

    String parameter = request.getParameter(PARAM_REMOVE);
    FileItem item = findFileItem(getSessionFileItems(request), parameter);
    if (item != null) {
      getSessionFileItems(request).remove(item);
      renderXmlResponse(request, response, DELETED_TRUE);
      logger.debug(
          "UPLOAD-SERVLET ("
              + request.getSession().getId()
              + ") removeUploadedFile: "
              + parameter
              + " "
              + item.getName()
              + " "
              + item.getSize());
    } else {
      renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
      logger.info(
          "UPLOAD-SERVLET ("
              + request.getSession().getId()
              + ") removeUploadedFile: "
              + parameter
              + " unable to delete file because it isn't in session.");
    }

    return item;
  }
Ejemplo n.º 4
0
 /** Returns the size of the file item in bytes. */
 public long getFileSize() {
   long result = 0;
   if (fileItem != null) {
     result = fileItem.getSize();
   }
   return result;
 }
Ejemplo n.º 5
0
 public Map upload(HttpServletRequest request, FileItem item) {
   Map mapList = new HashMap();
   try {
     if (item.isFormField()) {
       // 普通表单
     } else {
       String fieldName = item.getFieldName();
       String fileName = item.getName();
       // 如果文件域没有填写内容,或者填写的文件不存在
       if ("".equals(fileName) || item.getSize() == 0) {
         return mapList;
       }
       String userfilepath = request.getRealPath("upload");
       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);
       mapList.put("fieldname", fieldName);
       mapList.put(
           "filename",
           fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length()));
       mapList.put("extname", extName);
       mapList.put("filepath", userfilepath + date + newfilename);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return mapList;
 }
Ejemplo n.º 6
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);
    }
  }
Ejemplo n.º 7
0
  @SuppressWarnings("unchecked")
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.info("upload start------");
    request.setCharacterEncoding("UTF-8");
    StringBuffer savePath = new StringBuffer("/mnt/web/static/images/album/");
    Calendar c = Calendar.getInstance();
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd/");
    String date = df.format(c.getTime());
    savePath.append(date);
    File dir = new File(savePath.toString());
    if (!dir.exists()) {
      dir.mkdirs();
    }
    DiskFileItemFactory fac = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setHeaderEncoding("UTF-8");
    List<FileItem> list = null;
    try {
      list = upload.parseRequest(request);
    } catch (FileUploadException e) {
      log.error(e.getMessage(), e);
      return;
    }
    log.info("file size:{}", list.size());
    for (FileItem it : list) {
      if (!it.isFormField()) {
        String name = it.getName();
        long size = it.getSize();
        String type = it.getContentType();
        log.info("name:{},size:{},type:{}", name, size, type);
        if (StringUtils.isBlank(name)) {
          continue;
        }
        String extName = null;
        if (name.lastIndexOf(".") >= 0) {
          extName = name.substring(name.lastIndexOf("."));
        }
        File file = null;
        do {
          name = UUIDUtil.getRandomUUID();
          file = new File(savePath + name + extName);
        } while (file.exists());
        File saveFile = new File(savePath + name + extName);
        log.info("path:{}", saveFile.getAbsolutePath());
        try {
          it.write(saveFile);
          albumService.newPhoto(1, saveFile.getAbsolutePath(), "none");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    response.getWriter().write("1");
    log.info("upload end------");
  }
Ejemplo n.º 8
0
 private void processFile(FileItem item) {
   imageSize = item.getSize();
   try {
     imageIs = item.getInputStream();
   } catch (IOException e) {
     imageIs = null;
     imageSize = 0;
   }
 }
  public String validationInfo() throws Exception {
    StringBuffer stringBuffer = new StringBuffer();

    String command = (String) this.getRequestHashMap().get(GLOBALS.ADMINCOMMAND);
    if (command == null || command.compareTo(UPDATEPRODUCT) != 0) {
      return CommonSeps.getInstance().SPACE;
    }

    stringBuffer.append(new BasicItemValidation(this.itemInterface).validationInfo());

    StoreFrontInterface storeFrontInterface =
        StoreFrontFactory.getInstance(this.getWeblisketSession().getStoreName());

    String fullCategory =
        (String) URLGLOBALS.getWebappPath()
            + storeFrontInterface.getCurrentHostNamePath()
            + // storeFrontInterface.getCategoryPath() +
            this.itemInterface.getCategory();

    if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
        abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
      LogUtil.put(LogFactory.getInstance("Category: " + fullCategory, this, "validationInfo()"));
    }

    try {
      if (InventoryEntityFactory.getInstance()
              .getInventoryEntityInstance()
              .getItem(this.itemInterface.getId())
          == null) {
        stringBuffer.append("Item does not exist.<br>");
      }
    } catch (MoneyException e) {
      if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
          abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
        LogUtil.put(
            LogFactory.getInstance("Existing Item With MoneyException", this, "validationInfo()"));
      }
    }

    Object object = this.getRequestHashMap().get(BasicItemData.IMAGE);

    if (HttpFileUploadUtil.getInstance().isValid(object)) {
      FileItem fileItem = (FileItem) object;

      long size = fileItem.getSize();
      String fileName = fileItem.getName();
      String fileItemFieldName = fileItem.getFieldName();

      this.validationInfo(stringBuffer, fileName, fileItemFieldName, size);
    }

    // else stringBuffer.append("Image File Form Data Error");

    return stringBuffer.toString();
  }
  /**
   * Responsible for constructing a FileBean object for the named file parameter. If there is no
   * file parameter with the specified name this method should return null.
   *
   * @param name the name of the file parameter
   * @return a FileBean object wrapping the uploaded file
   */
  public FileBean getFileParameterValue(String name) {
    final FileItem item = this.files.get(name);
    if (item == null
        || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) {
      return null;
    } else {
      // Attempt to ensure the file name is just the basename with no path included
      String filename = item.getName();
      int index;
      if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) {
        index = filename.lastIndexOf('\\');
      } else {
        index = filename.lastIndexOf('/');
      }
      if (index >= 0 && index + 1 < filename.length() - 1) {
        filename = filename.substring(index + 1);
      }

      // Use an anonymous inner subclass of FileBean that overrides all the
      // methods that rely on having a File present, to use the FileItem
      // created by commons upload instead.
      return new FileBean(null, item.getContentType(), filename, this.charset) {
        @Override
        public long getSize() {
          return item.getSize();
        }

        @Override
        public InputStream getInputStream() throws IOException {
          return item.getInputStream();
        }

        @Override
        public void save(File toFile) throws IOException {
          try {
            item.write(toFile);
            delete();
          } catch (Exception e) {
            if (e instanceof IOException) {
              throw (IOException) e;
            } else {
              IOException ioe = new IOException("Problem saving uploaded file.");
              ioe.initCause(e);
              throw ioe;
            }
          }
        }

        @Override
        public void delete() throws IOException {
          item.delete();
        }
      };
    }
  }
Ejemplo n.º 11
0
  @Test
  public void testGetSize() {
    WFileWidget widget = new WFileWidget();
    setActiveContext(createUIContext());

    Assert.assertEquals("Size should be 0 by default", 0, widget.getSize());

    // Set file on widget
    widget.setData(TEST_FILE_ITEM_WRAP);
    Assert.assertEquals("Incorrect size returned", TEST_FILE_ITEM.getSize(), widget.getSize());
  }
  private DocumentoProyecto getDocumentoProyecto(
      Long proy_proy,
      Map<String, Object> mapRequestParameters,
      Usuario usuario,
      String observacionCreacion) {
    DocumentoProyecto documento = null;
    try {

      DocumentoProyectoServicio docServicio = DocumentoProyectoServicio.getInstance();
      Long idDocumento = docServicio.getSiguienteID();
      Long version = docServicio.getSiguienteVersion(proy_proy);

      FileItem fileItem = (FileItem) mapRequestParameters.get("DocumentoProyecto");

      String rutabase = DocumentoProyectoServicio.getInstance().getRutaBaseDeArchivos();

      if (fileItem != null) {

        String nombreReal = FilenameUtils.getBaseName(fileItem.getName());
        String extension = FilenameUtils.getExtension(fileItem.getName());
        String nombreEnServidor =
            DocumentoProyectoServicio.getInstance()
                .construirNombreDeArchivo(proy_proy, idDocumento, version);

        String ruta = ServletUtils.copyFileItem(rutabase, fileItem, "/" + nombreEnServidor);

        Long longBytes = fileItem.getSize();
        File file = new File(ruta);
        System.out.println(file.exists());
        Long checkSum = FileUtils.checksumCRC32(file);

        DocumentoProyecto documentoProyecto = new DocumentoProyecto();
        documentoProyecto.setDproy_extension(extension);
        documentoProyecto.setDproy_falm(ServerServicio.getInstance().getSysdate());
        documentoProyecto.setDproy_dproy(idDocumento);
        documentoProyecto.setDproy_proy(proy_proy);
        documentoProyecto.setDproy_bytes(longBytes.toString());
        documentoProyecto.setDproy_nombre(nombreReal);
        documentoProyecto.setDproy_hash(checkSum.toString());
        documentoProyecto.setDproy_url(ruta);
        documentoProyecto.setDproy_vers(version);
        documentoProyecto.setDproy_usua(usuario.getUsua_usua());
        documentoProyecto.setDproy_observ(observacionCreacion);

        documento = documentoProyecto;
      }

      return documento;

    } catch (Throwable e) {
      SimpleLogger.error("Error obteniendo la informacion del documento de proyecto", e);
      return null;
    }
  }
  /**
   * Get a generic attributes response from a file item
   *
   * @param fileItem The file item
   * @param entry The entry
   * @param bCreatePhysicalFile True to create the physical file associated with the file of the
   *     response, false otherwise. Note that the physical file will never be saved in the database
   *     by this method, like any other created object.
   * @return The created response
   */
  private Response getResponseFromFile(
      FileItem fileItem, Entry entry, boolean bCreatePhysicalFile) {
    if (fileItem instanceof GenAttFileItem) {
      GenAttFileItem genAttFileItem = (GenAttFileItem) fileItem;

      if (genAttFileItem.getIdResponse() > 0) {
        Response response = ResponseHome.findByPrimaryKey(genAttFileItem.getIdResponse());
        response.setEntry(entry);
        response.setFile(FileHome.findByPrimaryKey(response.getFile().getIdFile()));

        if (bCreatePhysicalFile) {
          response.getFile().getPhysicalFile().setValue(fileItem.get());
        }

        return response;
      }
    }

    Response response = new Response();
    response.setEntry(entry);

    File file = new File();
    file.setTitle(fileItem.getName());
    file.setSize(
        (fileItem.getSize() < Integer.MAX_VALUE) ? (int) fileItem.getSize() : Integer.MAX_VALUE);

    if (bCreatePhysicalFile) {
      file.setMimeType(FileSystemUtil.getMIMEType(file.getTitle()));

      PhysicalFile physicalFile = new PhysicalFile();
      physicalFile.setValue(fileItem.get());
      file.setPhysicalFile(physicalFile);
    }

    response.setFile(file);

    return response;
  }
  protected void processFile(FileItem item, String name, MutableRequest request) {
    try {
      String fileName = FilenameUtils.getName(item.getName());
      UploadedFile upload =
          new DefaultUploadedFile(
              item.getInputStream(), fileName, item.getContentType(), item.getSize());
      request.setParameter(name, name);
      request.setAttribute(name, upload);

      logger.debug("Uploaded file: {} with {}", name, upload);
    } catch (IOException e) {
      throw new InvalidParameterException("Can't parse uploaded file " + item.getName(), e);
    }
  }
Ejemplo n.º 15
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();
    }
  }
Ejemplo n.º 16
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;
 }
  /**
   * Uploads the file containing the video and that is identified by the specified field name.
   *
   * @param items the items of the form. One of them is containg the video file.
   * @param itemKey the key of the item containing the video.
   * @param pageContext the context of the page displaying the form.
   * @throws Exception if an error occurs while uploading the video file.
   * @return the identifier of the uploaded attached video file.
   */
  private String uploadVideoFile(
      final List<FileItem> items, final String itemKey, final PagesContext pageContext)
      throws Exception {
    String attachmentId = "";

    FileItem item = FileUploadUtil.getFile(items, itemKey);
    if (!item.isFormField()) {
      String componentId = pageContext.getComponentId();
      String userId = pageContext.getUserId();
      String objectId = pageContext.getObjectId();
      String logicalName = item.getName();
      long size = item.getSize();
      if (StringUtil.isDefined(logicalName)) {
        if (!FileUtil.isWindows()) {
          logicalName = logicalName.replace('\\', File.separatorChar);
          SilverTrace.info(
              "form",
              "VideoFieldDisplayer.uploadVideoFile",
              "root.MSG_GEN_PARAM_VALUE",
              "fullFileName on Unix = " + logicalName);
        }

        logicalName =
            logicalName.substring(
                logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
        String type = FileRepositoryManager.getFileExtension(logicalName);
        String mimeType = item.getContentType();
        String physicalName = Long.toString(System.currentTimeMillis()) + "." + type;
        File dir = getVideoPath(componentId, physicalName);
        item.write(dir);
        AttachmentDetail attachmentDetail =
            createAttachmentDetail(
                objectId,
                componentId,
                physicalName,
                logicalName,
                mimeType,
                size,
                VideoFieldDisplayer.CONTEXT_FORM_VIDEO,
                userId);
        attachmentDetail = AttachmentController.createAttachment(attachmentDetail, true);
        attachmentId = attachmentDetail.getPK().getId();
      }
    }

    return attachmentId;
  }
Ejemplo n.º 18
0
  public void parseRequest(
      List fileItems, HashMap<String, String> arrParam, ArrayList<FileItem> fi, boolean fileUpload)
      throws ServiceException {

    FileItem fi1 = null;
    for (Iterator k = fileItems.iterator(); k.hasNext(); ) {
      fi1 = (FileItem) k.next();
      if (fi1.isFormField()) {
        arrParam.put(fi1.getFieldName(), fi1.getString());
      } else {
        if (fi1.getSize() != 0) {
          fi.add(fi1);
          fileUpload = true;
        }
      }
    }
  }
  private void uploadFile(File file) throws Exception {
    if (fileItem == null) return;

    long fileSize = fileItem.getSize();
    if (sizeMax > -1 && fileSize > super.sizeMax) {
      String message =
          String.format(
              "the request was rejected because its size (%1$s) exceeds the configured maximum (%2$s)",
              fileSize, super.sizeMax);

      throw new org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException(
          message, fileSize, super.sizeMax);
    }

    String name = fileItem.getName();
    fileItem.write(file);
  }
Ejemplo n.º 20
0
  public KwlReturnObject uploadFile(FileItem fi, String userid) throws ServiceException {
    Docs docObj = new Docs();
    List ll = new ArrayList();
    int dl = 0;
    try {
      String fileName = new String(fi.getName().getBytes(), "UTF8");
      String Ext = "";
      String a = "";

      if (fileName.contains(".")) {
        Ext = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
        a = Ext.toUpperCase();
      }

      User userObj = (User) hibernateTemplate.get(User.class, userid);
      docObj.setDocname(fileName);
      docObj.setUserid(userObj);
      docObj.setStorename("");
      docObj.setDoctype(a + " " + "File");
      docObj.setUploadedon(new Date());
      docObj.setStorageindex(1);
      docObj.setDocsize(fi.getSize() + "");

      hibernateTemplate.save(docObj);

      String fileid = docObj.getDocid();
      if (Ext.length() > 0) {
        fileid = fileid + Ext;
      }
      docObj.setStorename(fileid);

      hibernateTemplate.update(docObj);

      ll.add(docObj);

      //            String temp = "/home/trainee";
      String temp = storageHandlerImplObj.GetDocStorePath();
      uploadFile(fi, temp, fileid);
    } catch (Exception e) {
      throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
Ejemplo n.º 21
0
  /**
   * Get a file contained in the request from the name of the parameter
   *
   * @param strFileInputName name of the file parameter of the request
   * @param request the request
   * @return file the file contained in the request with the given parameter key
   */
  private static File getFileData(String strFileInputName, HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    FileItem fileItem = multipartRequest.getFile(strFileInputName);

    if ((fileItem != null)
        && (fileItem.getName() != null)
        && !EMPTY_STRING.equals(fileItem.getName())) {
      File file = new File();
      PhysicalFile physicalFile = new PhysicalFile();
      physicalFile.setValue(fileItem.get());
      file.setTitle(FileUploadService.getFileNameOnly(fileItem));
      file.setSize((int) fileItem.getSize());
      file.setPhysicalFile(physicalFile);
      file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)));

      return file;
    }

    return null;
  }
Ejemplo n.º 22
0
 protected Map<String, String> getFileItemsSummary(
     HttpServletRequest request, Map<String, String> ret) {
   if (ret == null) {
     ret = new HashMap<String, String>();
   }
   @SuppressWarnings("unchecked")
   List<FileItem> s = (List<FileItem>) request.getSession().getAttribute(ATTR_LAST_FILES);
   if (s != null) {
     for (FileItem i : s) {
       if (false == i.isFormField()) {
         ret.put("ctype", i.getContentType() != null ? i.getContentType() : "unknown");
         ret.put("size", "" + i.getSize());
         ret.put("name", "" + i.getName());
         ret.put("field", "" + i.getFieldName());
       }
     }
     ret.put(TAG_FINISHED, "ok");
   }
   return ret;
 }
Ejemplo n.º 23
0
 /** 批量上传 @作者: 卜繁晟 @创时: 2013-2-9 下午5:04:24 */
 public List<Map> upload(HttpServletRequest request, List<FileItem> items) {
   String userfilepath = "";
   List<Map> resultList = new ArrayList<Map>();
   try {
     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;
 }
Ejemplo n.º 24
0
  private ExtendedMap parseMultiPartRequest(HttpServletRequest request)
      throws FileUploadException, IOException {
    ExtendedMap formItems = new ExtendedMap();
    List paramList = fileUpload.parseRequest(request);
    for (Object parameter : paramList) {
      FileItem fileItem = (FileItem) parameter;

      String name = fileItem.getFieldName();

      if (fileItem.isFormField()) {
        String value = fileItem.getString("UTF-8");
        if (formItems.containsKey(name)) {
          ArrayList<Object> values = new ArrayList<Object>();
          Object obj = formItems.get(name);
          if (obj instanceof Object[]) {
            String[] objArray = (String[]) obj;
            for (int i = 0; i < objArray.length; i++) {
              values.add(objArray[i]);
            }
          } else {
            values.add(obj);
          }
          values.add(value);
          formItems.put(name, values.toArray(new String[values.size()]));
        } else {
          formItems.put(name, value);
        }
      } else {
        if (fileItem.getSize() > 0) {
          if (formItems.containsKey(name)) {
            ArrayList<Object> values = new ArrayList<Object>();
            Object obj = formItems.get(name);
            if (obj instanceof FileItem[]) {
              FileItem[] objArray = (FileItem[]) obj;
              for (int i = 0; i < objArray.length; i++) {
                values.add(objArray[i]);
              }
            } else {
              values.add(obj);
            }
            values.add(fileItem);
            formItems.put(name, values.toArray(new FileItem[values.size()]));
          } else {
            formItems.put(name, fileItem);
          }
        }
      }
    }

    // Add parameters from url
    Map paramMap = URLUtil.decodeParameterMap(request.getParameterMap());
    for (Object parameterEntry : paramMap.entrySet()) {
      Map.Entry entry = (Map.Entry) parameterEntry;
      String key = (String) entry.getKey();
      String[] values = (String[]) entry.getValue();
      for (String value : values) {
        formItems.put(key, value);
      }
    }

    // Remove all empty parameters that are NOT in an array
    ArrayList<String> remove = new ArrayList<String>();
    for (Object parameterKey : formItems.keySet()) {
      String key = (String) parameterKey;
      Object value = formItems.get(key);
      if (!(value instanceof String[])
          && value instanceof String
          && ((String) value).length() == 0) {
        remove.add(key);
      }
    }
    for (String key : remove) {
      formItems.remove(key);
    }

    return formItems;
  }
  @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);
    }
  }
Ejemplo n.º 26
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Retrieving the file upload defaults from pentaho.xml
      String relativePath =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/relative-path",
              String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH)); // $NON-NLS-1$
      String maxFileLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-file-limit", String.valueOf(MAX_FILE_SIZE)); // $NON-NLS-1$
      String maxFolderLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-folder-limit",
              String.valueOf(MAX_FOLDER_SIZE)); // $NON-NLS-1$

      response.setContentType("text/plain");
      FileItem uploadItem = getFileItem(request);
      if (uploadItem == null) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0001_NO_FILE_TO_UPLOAD"));
        return;
      }
      if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
        response
            .getWriter()
            .write(
                Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0003_FILE_TOO_BIG"));
        return;
      }

      String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);

      File pathDir = new File(path);
      // create the path if it doesn't exist yet
      if (!pathDir.exists()) {
        pathDir.mkdirs();
      }

      if (uploadItem.getSize() + getFolderSize(pathDir) > Long.parseLong(maxFolderLimit)) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"));
        return;
      }
      byte[] fileContents = uploadItem.get();
      UUID id = UUIDUtil.getUUID();
      String filename = id.toString() + CSV_EXT;

      if (doesFileExists(new File(path + filename))) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0002_FILE_ALREADY_EXIST"));
        return;
      }
      FileOutputStream outputStream = new FileOutputStream(path + filename);
      outputStream.write(fileContents);
      outputStream.flush();
      outputStream.close();
      response.getWriter().write(new String(filename));
    } catch (Exception e) {
      response
          .getWriter()
          .write(
              Messages.getInstance()
                  .getErrorString(
                      "UploadFileServlet.ERROR_0005_UNKNOWN_ERROR", e.getLocalizedMessage()));
    }
  }
  public Boolean isValid() {
    try {
      String command = (String) this.getRequestHashMap().get(GLOBALS.ADMINCOMMAND);

      if (command == null || command.compareTo(UPDATEPRODUCT) != 0) {
        if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
            abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
          LogUtil.put(LogFactory.getInstance("Invalid AdminCommand=" + command, this, "isValid()"));
        }
        return Boolean.FALSE;
      }

      if (new BasicItemValidation(this.itemInterface).isValid() == Boolean.FALSE) {
        if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
            abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
          LogUtil.put(LogFactory.getInstance("BasicItem is not valid", this, "isValid()"));
        }
        return Boolean.FALSE;
      }

      StoreFrontInterface storeFrontInterface =
          StoreFrontFactory.getInstance(this.getWeblisketSession().getStoreName());

      StringBuffer stringBuffer = new StringBuffer();

      stringBuffer.append(URLGLOBALS.getWebappPath());
      stringBuffer.append(storeFrontInterface.getCurrentHostNamePath());
      // storeFrontInterface.getCategoryPath() +
      stringBuffer.append(this.itemInterface.getCategory());

      String fullCategory = stringBuffer.toString();

      AbFile categoryFile = new AbFile(fullCategory);
      if (!categoryFile.isDirectory()) {
        if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
            abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
          LogUtil.put(
              LogFactory.getInstance(
                  "Category Does Not Exist: " + fullCategory, this, "isValid()"));
        }
        return Boolean.FALSE;
      }

      InventoryEntity inventoryEntity =
          InventoryEntityFactory.getInstance().getInventoryEntityInstance();

      if (inventoryEntity.getItem(this.itemInterface.getId()) == null) {
        return Boolean.FALSE;
      }

      Object object = this.getRequestHashMap().get(BasicItemData.IMAGE);

      if (HttpFileUploadUtil.getInstance().isValid(object)) {
        FileItem fileItem = (FileItem) object;

        long size = fileItem.getSize();
        String fileName = fileItem.getName();

        HttpFileUploadUtil.log(fileItem);

        if (this.isValid(fileName, size) == Boolean.FALSE) {
          return Boolean.FALSE;
        }
      }

      return Boolean.TRUE;
    } catch (Exception e) {
      if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
          abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
        LogUtil.put(LogFactory.getInstance("Exception in validation", this, "isValid()", e));
      }

      return Boolean.FALSE;
    }
  }
Ejemplo n.º 28
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);
    }
  }
Ejemplo n.º 29
0
  /**
   * 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);
    }
  }
Ejemplo n.º 30
0
 /** Returns the size of the file. */
 public long getSize() {
   return fileItem.getSize();
 }