コード例 #1
0
 /** A convenience method to write the uploaded file to disk. */
 public void write(File file) {
   try {
     fileItem.write(file); // throws Exception
   } catch (Exception e) {
     throw new RuntimeException("Writing uploaded file to disk failed (" + this + ")", e);
   }
 }
コード例 #2
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    // 设置上传文件大小的上限,-1表示无上限
    fileUpload.setSizeMax(-1);
    // 上传文件,解析表单中包含的文件字段和普通字段
    try {
      List<FileItem> items = fileUpload.parseRequest(request);
      if (items.size() > 0) {
        FileItem item = (FileItem) items.get(0);
        String name = item.getName();
        String path = getServletContext().getRealPath(Constants.UPLOAD_IMG_PATH) + "/" + name;
        logger.info("上传用户图片信息,图片名:" + name + ";上传路径:" + path);
        // 实现图片上传
        try {
          item.write(new File(path));
          // 就用户头像路径保存.
          User user = new User();
          user.setPhone(request.getHeader("owner"));
          user.setImgPath(Constants.UPLOAD_IMG_PATH + "/" + name);
          userService.saveOrUpdateUserInfo(user);

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

    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #3
0
  /**
   * Override executeAction to save the received files in a custom place and delete this items from
   * session.
   */
  @Override
  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
      throws UploadActionException {
    String response = "";
    HttpSession session = request.getSession(true);
    if (sessionFiles.size() == 0) {
      LOG.info("No hay imagenes en la session");
      return "No hay imagenes en la session";
    }
    if (session.getAttribute(ATTR_ARCHIVOS) == null)
      session.setAttribute(ATTR_ARCHIVOS, new ArrayList<String>());

    List<String> photos = (List<String>) session.getAttribute(ATTR_ARCHIVOS);

    for (FileItem item : sessionFiles) {
      if (false == item.isFormField()) {
        try {
          // / Create a new file based on the remote file name in the
          // client
          // String saveName =
          // item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+",
          // "_");
          // File file =new File("/tmp/" + saveName);

          // / Create a temporary file placed in /tmp (only works in
          // unix)
          // File file = File.createTempFile("upload-", ".bin", new
          // File("/tmp"));

          // / Create a temporary file placed in the default system
          // temp folder

          String name = item.getName();
          int posPunto = name.lastIndexOf(".");
          String ext = name.substring(posPunto + 1);

          File file = File.createTempFile("gha", "." + ext);

          item.write(file);

          // / Save a list with the received files
          receivedFiles.put(item.getFieldName(), file);
          receivedContentTypes.put(item.getFieldName(), item.getContentType());
          photos.add(file.getName());

          // / Send a customized message to the client.
          response += file.getName();

        } catch (Exception e) {
          throw new UploadActionException(e);
        }
      }
    }

    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send your customized message to the client.
    return response;
  }
コード例 #4
0
ファイル: FileHandler.java プロジェクト: shshen/simplemr
 @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;
   }
 }
コード例 #5
0
ファイル: CardController.java プロジェクト: hgd250/dl234
  /**
   * 注销健康卡提交页
   *
   * @param model
   * @param mfile
   * @author 韩友军<*****@*****.**>
   * @since 2012-11-20下午12:57:08
   */
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/doCancelCardByExcel.html", method = RequestMethod.POST)
  public String doCancelCardByExcelAction(ModelMap model, HttpServletRequest request) {

    DiskFileItemFactory objDiskFileItemFactory = new DiskFileItemFactory();
    objDiskFileItemFactory.setSizeThreshold(1024 * 1024); // 缓存
    ServletFileUpload objServletFileUpload = new ServletFileUpload(objDiskFileItemFactory);

    try {
      List<FileItem> fileItems = objServletFileUpload.parseRequest(request);
      Iterator<FileItem> iterator = fileItems.iterator();
      while (iterator.hasNext()) {
        FileItem fileItem = (FileItem) iterator.next();
        if (!fileItem.isFormField()) {
          String strPath = this.context.getRealPath("/upload/");
          File file = new File(strPath + new Date().getTime() + ".xls");
          fileItem.write(file);
          String strFilePath = file.getPath();
          Map<String, Object> mapData = cardBO.cancelCard(strFilePath);
          model.put("data", mapData);
          model.put("success", true);
        }
      }
    } catch (Exception e) {
      model.put("success", false);
    }
    return "card/do_cancel_card_by_excel.html";
  }
コード例 #6
0
 @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();
   }
 }
コード例 #7
0
  protected File forceToFile(FileItem fileItem) throws IOException, ServletException {
    if (fileItem.isInMemory()) {
      String name = fileItem.getName();

      if (null == name) {
        throw new IllegalArgumentException("FileItem has null name");
      }

      // some browsers (IE, Chrome) pass an absolute filename, we just want the name of the file, no
      // paths
      name = name.replace('\\', '/');
      if (name.length() > 2 && name.charAt(1) == ':') {
        name = name.substring(2);
      }
      name = new File(name).getName();

      File tmpFile = File.createTempFile(name, null);
      try {
        fileItem.write(tmpFile);
        return tmpFile;
      } catch (Exception e) {
        throw new ServletException("Failed to persist uploaded file to disk", e);
      }
    } else {
      return ((DiskFileItem) fileItem).getStoreLocation();
    }
  }
コード例 #8
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;
 }
コード例 #9
0
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					File tempFile = new File(item.getName());
					file = new File(sc.getRealPath("/") + savePath, tempFile
							.getName());
					item.write(file);
				}
			}
		} catch (Exception e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送出了异常", e);
		}
		return file;
	}
コード例 #10
0
ファイル: UploadBOM.java プロジェクト: call4piyush/STAR
  @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);
    }
  }
コード例 #11
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));
      }
    }
  }
コード例 #12
0
ファイル: Upload.java プロジェクト: chenvwei/osight
  @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------");
  }
コード例 #13
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();
    }
  }
コード例 #14
0
ファイル: AdminAgent.java プロジェクト: isuruw/wso2-axis2
  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);
  }
コード例 #15
0
ファイル: UsersResource.java プロジェクト: flacro/photowall
  @Post
  public Representation update(Representation entity) {
    DomRepresentation r = null;
    try {
      int userid = Integer.parseInt((String) getRequest().getAttributes().get("userid"));
      Users u = userservice.getUsers(userid);
      String fname = u.getLogo();
      // upload picture
      ResourceBundle rb = ResourceBundle.getBundle("config");
      String path = rb.getString("albumpath");
      String fileName = "";
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // Configure the factory here, if desired.
      ServletFileUpload upload = new ServletFileUpload(factory);
      // Configure the uploader here, if desired.
      List fileItems = upload.parseRequest(ServletUtils.getRequest(getRequest()));
      Iterator iter = fileItems.iterator();
      for (; iter.hasNext(); ) {
        FileItem fileItem = (FileItem) iter.next();
        if (fileItem.isFormField()) { // 当前是一个表单项
          System.out.println(
              "form field : " + fileItem.getFieldName() + ", " + fileItem.getString());
        } else {
          // 当前是一个上传的文件
          fileName = fileItem.getName();
          String extension = fileName.substring(fileName.lastIndexOf("."));
          if (fname == null || fname.equals("")) {
            Random random = new Random(10);
            int n = random.nextInt(10000);
            fileName = new Date().getTime() + "-" + n + extension;
          } else fileName = fname;
          fileItem.write(new File(path + fileName));
        }
        // 只处理第一张图片
        break;
      }

      // 生成XML表示
      r = new DomRepresentation(MediaType.TEXT_XML);
      Document doc = r.getDocument();
      Element root = doc.createElement("varkrs");
      root.setAttribute("id", "" + u.getId());
      root.setAttribute("name", u.getUsername());
      root.setAttribute("gender", "" + u.getGender());
      root.setAttribute("grade", "" + u.getGrade());
      root.setAttribute("logo", u.getLogo());
      doc.appendChild(root);
      return r;
    } catch (Exception e) {
      LogDetail.logexception(e);
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return null;
    }
  }
コード例 #16
0
 public void store(String msisdn, List<FileItem> fileItems, String path) {
   for (FileItem fileItem : fileItems) {
     if (fileItem.isFormField()) continue;
     File savedFile = new File(path + "/" + msisdn + "_" + fileItem.getFieldName() + ".wav");
     try {
       savedFile.createNewFile();
       fileItem.write(savedFile);
       log.info("recorded file: " + savedFile);
     } catch (Exception e) {
       log.error("error in creating file " + savedFile, e);
     }
   }
 }
コード例 #17
0
 /**
  * Schreibt Datei beim &uuml;bergebenen absoluten Dateipfad
  *
  * @param item Zu schreibende Datei
  * @param path Absoluter Dateipfad
  * @return &uuml;bergebene Datei bei erfolgreichem Speichern, sonst null
  */
 public File write(FileItem item, File path) {
   File written = null;
   try {
     if (!path.getParentFile().exists()) {
       path.getParentFile().mkdirs();
     }
     item.write(path);
     written = path;
   } catch (Exception ex) {
     Logger.getLogger(FileSystemUtil.class.getName()).log(Level.SEVERE, null, ex);
   }
   return written;
 }
コード例 #18
0
 public void uploadFile(FileItem fi, String destinationDirectory, String fileName)
     throws ServiceException {
   try {
     File destDir = new File(destinationDirectory);
     if (!destDir.exists()) {
       destDir.mkdirs();
     }
     File uploadFile = new File(destinationDirectory + "/" + fileName);
     fi.write(uploadFile);
   } catch (Exception ex) {
     throw ServiceException.FAILURE("documentDAOImpl.uploadFile", ex);
   }
 }
コード例 #19
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    OSParameterFile.NAME = OSParameterFile.setParameterFile(request);
    // first check if the upload request coming in is a multipart request
    // boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // if not, send to message page with the error message
    // if(!isMultipart){
    //	request.setAttribute("msg", "Request was not multipart!");
    //	request.getRequestDispatcher("msg.jsp").forward(request, response);
    //	return;
    // }
    // Parse the request
    // List  items = upload.parseRequest( request) ;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Configure the factory here, if desired.
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Configure the uploader here, if desired.
    PrintWriter out = response.getWriter();
    try {
      java.util.List fileItems = upload.parseRequest(request);
      FileItem item;
      String fileName = "";
      item = (FileItem) fileItems.get(0);
      fileName = item.getName();
      String path = OSParameter.TEMP_FILE_FOLDER; // "/home/kmartin/temp/";
      File uploadedFile = new File(path + fileName);
      try {
        item.write(uploadedFile);
      } catch (java.lang.Exception ioe) {
        out.println("<html>");
        out.println("There was an error trying to save the uploaded file.");
        out.println("</html>");
        out.println("\r\n");
      }
      out.println("<html>");
      out.println(
          "The file "
              + fileName
              + " was successfuly uploaded and saved on the following server directory:");
      out.println(OSParameter.TEMP_FILE_FOLDER + fileName);
      out.println("</html>");
      out.println("\r\n");
    } catch (FileUploadException fe) {
      out.println("<html>");
      out.println("There was an error getting the file.");
      out.println(fe);
      out.println("</html>");
      out.println("\r\n");
    }
  }
コード例 #20
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;
  }
コード例 #21
0
ファイル: WebUtils.java プロジェクト: 7owl/uzuer
  public static boolean upload(FileItem fileItem, String fileName) {

    File file = new File(fileName);
    if (!file.getParentFile().exists()) {
      file.getParentFile().mkdirs();
    }

    try {
      fileItem.write(file);
    } catch (Exception e) {
      return false;
    }

    return true;
  }
コード例 #22
0
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse resp)
     throws ServletException, IOException {
   request.setCharacterEncoding("UTF-8");
   String FSP = System.getProperty("file.separator");
   String LSP = System.getProperty("line.separator");
   String url = "";
   JSONObject backJsonObejct = new JSONObject();
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   String result;
   String fileName = "";
   try {
     List items = upload.parseRequest(request);
     Iterator iter = items.iterator();
     while (iter.hasNext()) {
       // 把实体换成map,然后保存
       FileItem item = (FileItem) iter.next();
       if (!item.isFormField()) {
         fileName = item.getName();
         String appendix = "";
         int indexOfDot = fileName.lastIndexOf(".");
         if (indexOfDot >= 0) {
           appendix = fileName.substring(indexOfDot);
         }
         byte[] fileBytes = item.get();
         String systemFileName = "upload-" + System.currentTimeMillis() + appendix;
         String filePath = "upload" + FSP + systemFileName;
         String realPath = request.getRealPath(FSP) + filePath;
         String dirPath = request.getRealPath(FSP) + "upload";
         File uploadedFile = new File(dirPath);
         if (!uploadedFile.isDirectory()) {
           uploadedFile.mkdirs();
         }
         System.out.println(item.getFieldName() + ":" + fileName);
         uploadedFile = new File(realPath);
         item.write(uploadedFile);
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   // 输出json
   PrintWriter pw = resp.getWriter();
   pw.append("{success:true}");
   pw.flush();
   pw.close();
 }
コード例 #23
0
  /**
   * 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;
  }
コード例 #24
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;
 }
コード例 #25
0
  @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");

  }
コード例 #26
0
ファイル: FotoUploadUtil.java プロジェクト: hezuo/veterinaria
  public File subirArchivo(FileItem item, String folderFotos) {
    File file = new File(item.getName());
    File folderFotosExisting = new File(folderFotos);

    if (!folderFotosExisting.exists()) {
      folderFotosExisting.mkdirs();
    }
    try {
      item.write(new File(folderFotos, file.getName()));
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }

    return file;
  }
コード例 #27
0
  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);
  }
コード例 #28
0
ファイル: AddXunCha2Servlet.java プロジェクト: trueck/LEIMS
  public void writeFile(FileItem fileItem, CompanyTime companyTime) throws Exception {
    if (fileItem != null) {
      /*
       * 1. 得到文件保存的路径
       */
      String root = this.getServletContext().getRealPath("/files/");
      /*
       * 2. 生成二层目录 1). 得到文件名称 2). 得到hashCode 3). 转发成16进制 4). 获取前二个字符用来生成目录
       */
      String filename = fileItem.getName(); // 获取上传的文件名称
      /*
       * 处理文件名的绝对路径问题
       */
      int index = filename.lastIndexOf(".");
      if (index != -1) {
        filename = filename.substring(index);
      }
      /*
       * 给文件名称添加uuid前缀,处理文件同名问题
       */
      String savename = UuidUtils.uuid() + "_" + filename;

      /*
       * 2. 获取hex的前两个字母,与root连接在一起,生成一个完整的路径
       */
      File dirFile = new File(root);

      /*
       * 3. 创建目录链
       */
      if (!dirFile.exists()) {
        dirFile.mkdirs();
      }

      /*
       * 4. 创建目录文件
       */
      File destFile = new File(dirFile, savename);
      /*
       * 5. 保存
       */
      fileItem.write(destFile);
      companyTime.setXunChaJiLu(savename);
    }
  }
コード例 #29
0
ファイル: PluginManager.java プロジェクト: kmaehashi/jenkins
  /** Uploads a plugin. */
  public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException {
    try {
      Jenkins.getInstance().checkPermission(UPLOAD_PLUGINS);

      ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

      // Parse the request
      FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
      String fileName = Util.getFileName(fileItem.getName());
      if ("".equals(fileName)) {
        return new HttpRedirect("advanced");
      }
      // we allow the upload of the new jpi's and the legacy hpi's
      if (!fileName.endsWith(".jpi") && !fileName.endsWith(".hpi")) {
        throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName));
      }

      // first copy into a temporary file name
      File t = File.createTempFile("uploaded", ".jpi");
      t.deleteOnExit();
      fileItem.write(t);
      fileItem.delete();

      final String baseName = identifyPluginShortName(t);

      pluginUploaded = true;

      // Now create a dummy plugin that we can dynamically load (the InstallationJob will force a
      // restart if one is needed):
      JSONObject cfg =
          new JSONObject()
              .element("name", baseName)
              .element("version", "0")
              . // unused but mandatory
              element("url", t.toURI().toString())
              .element("dependencies", new JSONArray());
      new UpdateSite(UpdateCenter.ID_UPLOAD, null).new Plugin(UpdateCenter.ID_UPLOAD, cfg)
          .deploy(true);
      return new HttpRedirect("../updateCenter");
    } catch (IOException e) {
      throw e;
    } catch (Exception e) { // grrr. fileItem.write throws this
      throw new ServletException(e);
    }
  }
コード例 #30
0
  public boolean saveAs(String folderName, String fileName, boolean isWebFolder) {
    folderName = (isWebFolder ? helper.getRealPath(folderName) : folderName);

    File dir = new File(folderName);
    if (!dir.exists()) {
      if (!dir.mkdirs()) return false;
    }

    File filePath = new File(folderName + File.separator + fileName);

    try {
      fileItem.write(filePath);
    } catch (Exception e) {
      System.out.println("[AttachedFile.saveAs]" + e.getMessage());
      return false;
    }

    return true;
  }