Example usage for org.apache.commons.fileupload FileItem write

List of usage examples for org.apache.commons.fileupload FileItem write

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem write.

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:com.wabacus.system.fileupload.AbsFileUpload.java

protected String doUploadFileAction(FileItem item, Map<String, String> mFormFieldValues, String orginalFilename,
        String configAllowTypes, List<String> lstConfigAllowTypes, String configDisallowTypes,
        List<String> lstConfigDisallowTypes) {
    String strmaxsize = mFormFieldValues.get(AbsFileUploadInterceptor.MAXSIZE_KEY);
    if (strmaxsize != null && !strmaxsize.trim().equals("")) {
        long lmaxsize = Long.parseLong(strmaxsize.trim());
        if (lmaxsize > 0 && lmaxsize < item.getSize())
            return "";
    }//  w  w w .j  a v  a  2s.  c  om
    if (!isInvalidUploadFileType(orginalFilename, configAllowTypes, lstConfigAllowTypes, configDisallowTypes,
            lstConfigDisallowTypes)) {
        return "??";
    }
    String savepathTmp = mFormFieldValues.get(AbsFileUploadInterceptor.SAVEPATH_KEY);
    String destfilenameTmp = mFormFieldValues.get(AbsFileUploadInterceptor.FILENAME_KEY);
    if (!Tools.isEmpty(savepathTmp) && !Tools.isEmpty(destfilenameTmp)) {
        try {
            savepathTmp = FilePathAssistant.getInstance().standardFilePath(savepathTmp + File.separator);
            FilePathAssistant.getInstance().checkAndCreateDirIfNotExist(savepathTmp);
            item.write(new File(savepathTmp + destfilenameTmp));
        } catch (Exception e) {
            log.error("" + orginalFilename + "" + savepathTmp + "", e);
            return "" + orginalFilename + "" + savepathTmp + "";
        }
    }
    return null;
}

From source file:com.silverpeas.blog.control.BlogSessionController.java

/**
 * Save the banner file./*from   ww w  .j a va2s  . co  m*/
 *
 * @throws BlogRuntimeException
 */
public void saveWallPaperFile(FileItem fileItemWallPaper) throws BlogRuntimeException {
    //extension
    String extension = FileRepositoryManager.getFileExtension(fileItemWallPaper.getName());
    if (extension != null && extension.equalsIgnoreCase("jpeg")) {
        extension = "jpg";
    }

    if (!"gif".equalsIgnoreCase(extension) && !"jpg".equalsIgnoreCase(extension)
            && !"png".equalsIgnoreCase(extension)) {
        throw new BlogRuntimeException("BlogSessionController.saveStyleSheetFile()",
                SilverpeasRuntimeException.ERROR, "blog.EX_EXTENSION_WALLPAPER");
    }

    //path to create the file
    String path = FileRepositoryManager.getAbsolutePath(this.getComponentId());

    //remove all wallpapers to ensure it is unique
    removeWallPaperFile();

    try {
        String nameFile = "banner." + extension.toLowerCase();
        File fileWallPaper = new File(path + File.separator + nameFile);

        //create the file
        fileItemWallPaper.write(fileWallPaper);

        //save the information
        this.wallPaper = new WallPaper();
        this.wallPaper.setName(nameFile);
        this.wallPaper.setUrl(FileServerUtils.getOnlineURL(this.getComponentId(), nameFile, nameFile,
                FileUtil.getMimeType(nameFile), ""));
        this.wallPaper.setSize(FileRepositoryManager.formatFileSize(fileWallPaper.length()));
    } catch (Exception ex) {
        throw new BlogRuntimeException("BlogSessionController.saveWallPaperFile()",
                SilverpeasRuntimeException.ERROR, "blog.EX_CREATE_WALLPAPER", ex);
    }
}

From source file:com.krawler.esp.servlets.importProjectPlanCSV.java

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {//from w w  w  . ja  v a  2s.  co m
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:productupdate.java

void getformdata() {
    try {//w  w w  .  j a va2s  .  co  m
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data

                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productid")) {
                    productid = data;
                } else if (h.equalsIgnoreCase("productname")) {
                    productname = data;

                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                } else if (h.equalsIgnoreCase("status")) {
                    System.out.println("status " + status);
                    status = data;
                }
            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        System.out.println("images " + image);
                        image = filename;
                    }
                }

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

}

From source file:adminpackage.adminview.ProductAddition.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/plain;charset=UTF-8");

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

    AdminViewProduct product = new AdminViewProduct();
    List<FileItem> items = upload.parseRequest(request);
    Iterator itr = items.iterator();
    String value = "defa";
    String url = "";
    while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
            String name = item.getFieldName();
            value = item.getString();/*from  ww w. ja v  a 2 s .c o  m*/
            switch (name) {
            case "pname":
                product.setName(value);
                break;
            case "quantity":
                product.setQuantity(Integer.parseInt(value));
                break;
            case "author":
                product.setAuthor(value);
                break;
            case "isbn":
                product.setISBN(Long.parseLong(value));
                break;
            case "description":
                product.setDescription(value);
                break;
            case "category":
                product.setCategory(value);
                break;
            case "price":
                product.setPrice(Integer.parseInt(value));
                break;
            }
        } else {

            //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName());
            //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName();
            UUID idOne = UUID.randomUUID();
            product.setImage(idOne.toString() + item.getName().substring(item.getName().length() - 4));
            item.write(new File(context.getRealPath("/pages/images/")
                    .replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp")
                    + idOne.toString() + item.getName().substring(item.getName().length() - 4)));
        }
    }

    PrintWriter out = response.getWriter();

    if (adminFacadeHandler.addBook(product)) {
        out.print("true");
    } else {
        //out.println("false");
        out.print("false");
    }
}

From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from  w  ww .  ja  va 2  s  . com*/
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdirs();
    }

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);

            //???IP
            String server_ip = (String) session.getAttribute("server_ip");
            if (server_ip == null) {
                server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP?
            }
            String url = "http://" + server_ip + currentPath.substring(2, currentPath.length());

            fileUrl = url + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = url + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

}

From source file:admin.controller.ServletUpdateFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w .  j ava  2  s. c  o  m*/
 *
 * @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
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = "";
    RequestDispatcher request_dispatcher;
    String fontname = null, fontid = null, lookid;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH;
        deletePath = AppConstants.BASE_FONT_UPLOAD_PATH;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(AppConstants.TMP_FOLDER));

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

            // 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>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("fontname")) {
                        fontname = fi.getString();
                    }
                    if (fieldName.equals("fontid")) {
                        fontid = fi.getString();
                        file_name_to_delete = font.getFileName(Integer.parseInt(fontid));
                    }

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    if (fileName != "") {

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = uploadPath + File.separator + fileName;
                        String delete_path = deletePath + File.separator + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            font.changeFont(Integer.parseInt(fontid), fontname, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while Updating fonts", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:com.globalsight.everest.webapp.pagehandler.administration.users.UserImportHandler.java

/**
 * Upload the xml file to tmp folder/*from   w  w w . ja  va2s  .co  m*/
 * 
 * @param request
 */
private File uploadFile(HttpServletRequest request) {
    File f = null;
    try {
        String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
                + File.separator + "tmp";
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = tmpDir + File.separator + originalFilePath;
                    f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
        return f;
    } catch (Exception e) {
        logger.error("File upload failed.", e);
        return null;
    }
}

From source file:fr.gael.dhus.service.ProductUploadService.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@Transactional(propagation = Propagation.REQUIRED)
public void upload(Long user_id, FileItem product, ArrayList<Long> collection_ids)
        throws UploadingException, RootNotModifiableException, ProductNotAddedException {
    //userService.getUser (userId);
    User owner = securityService.getCurrentUser();
    ArrayList<Collection> collections = new ArrayList<>();
    for (Long cId : collection_ids) {
        Collection c;/*  ww  w .  j a  v  a2s .  c om*/
        //         try
        //         {
        c = collectionService.getCollection(cId);
        //         }
        //         catch (CollectionNotExistingException e)
        //         {
        //            continue;
        //         }
        collections.add(c);
    }

    String fileName = product.getName();
    try {
        logger.info(new Message(MessageType.UPLOADS,
                owner.getUsername() + " tries to upload product '" + fileName + "'"));
        actionRecordWritterDao.uploadStart(fileName, owner.getUsername());
        if (fileName != null) {
            fileName = FilenameUtils.getName(fileName);
        }
        File path = null;
        try {
            path = incomingManager.getNewProductIncomingPath();
            if (path == null)
                throw new UnsupportedOperationException("Computed upload path is not available.");
        } catch (Exception e) {
            // actionRecordWritterDao.uploadFailed (fileName, owner);
            throw e;
        }
        File uploadedFile = new File(path, fileName);
        if (uploadedFile.createNewFile()) {
            product.write(uploadedFile);
        } else {
            throw new IOException("The file already exists in repository.");
        }
        //         uploadDone (uploadedFile.toURI ().toURL (), owner, collections);
        uploadService.addProduct(uploadedFile.toURI().toURL(), owner, collections);
    } catch (ProductNotAddedException e) {
        throw e;
    }
    //      catch (UploadingException e)
    //      {
    //         throw new UploadingException ("An error occured when uploading '" +
    //                  fileName + "'", e);
    //      }      
    catch (Exception e) {
        actionRecordWritterDao.uploadFailed(fileName, owner.getUsername());
        throw new UploadingException("An error occured when uploading '" + fileName + "'", e);
    }
}

From source file:Logic.UploadLogic.java

public void pictureUpload(HttpServletRequest request, UserDataBeans loginAccount, String contextPath) {
    for (int i = 0; i < 6; i++) {
    }/*from   w w  w .j  a  v a 2  s.  com*/
    PictureDataBeans picture = null;

    //?
    System.out.println("" + request.getRequestURI());
    String path = "/Users/gest/NetBeansProjects/WorkSpacesProto/web/common/image/";
    File newDirectry = new File(path + loginAccount.getUserName());

    //?????
    if (!newDirectry.exists() || newDirectry == null) {
        newDirectry.mkdir();
        System.out.println("?");
    }

    //??
    String dPath = newDirectry.getPath();

    //???
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);

    try {
        //????????
        List<FileItem> list = sfu.parseRequest(request);
        Iterator iterator = list.iterator();

        String pictureName = "";
        String extension = "";
        String comment = "????";
        int categoryID = 1;

        FileItem pictureData = null;

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

            //??
            if (!item.isFormField()) {
                pictureData = item;
                String itemName = item.getName();
                extension = itemName.substring(itemName.lastIndexOf("."));

                //()??   
            } else {
                System.out.println(item.getString("UTF-8"));
                switch (item.getFieldName()) {

                case "pictureName":
                    //?????
                    pictureName = item.getString("UTF-8");
                    //?????, [+]??
                    if (pictureName.isEmpty()) {
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        String strDate = sdf.format(date);
                        pictureName = "" + strDate;
                    }
                    break;

                case "category":
                    categoryID = Integer.parseInt(item.getString("UTF-8"));
                    break;

                case "comment":
                    comment = item.getString("UTF-8");
                    break;
                }
            }
        }

        pictureData.write(new File(dPath + "/" + pictureName + extension));
        //??, DB??
        String pPath = contextPath + "/common/image/" + loginAccount.getUserName() + "/" + pictureName
                + extension;
        picture = new PictureDataBeans((pictureName + extension), pPath, comment, categoryID,
                loginAccount.getUserName());
        picture.setPictureID(picture.hashCode());

        //DB??
        PictureDataDTO dto = new PictureDataDTO();
        picture.PDB2DTOMapping(dto, loginAccount.getUserID());
        PictureDataDAO.getInstance().setPictureData(dto);

    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }

}