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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:datalab.upo.ladonspark.controller.uploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w ww .  j  av  a 2s  .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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    List<objectresult> lor = new ArrayList<>();
    List<objectresult> loraux = new ArrayList<>();
    boolean result = false;
    String urlf = "";
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    // req es la HttpServletRequest que recibimos del formulario.
    // Los items obtenidos sern cada uno de los campos del formulario,
    // tanto campos normales como ficheros subidos.
    List items = upload.parseRequest(request);

    // Se recorren todos los items, que son de tipo FileItem
    for (Object item : items) {
        FileItem uploaded = (FileItem) item;

        // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero
        // subido donde nos interese
        if (!uploaded.isFormField()) {
            // No es campo de formulario, guardamos el fichero en algn sitio
            if (!uploaded.getName().equals("")) {
                urlf = uploaded.getName();
                File fichero = new File(this.getPath() + "src/main/webapp/algorithm/dataAlgoritm/",
                        uploaded.getName());
                uploaded.write(fichero);
            } else {
                result = true;
            }
        } else {
            // es un campo de formulario, podemos obtener clave y valor
            String key = uploaded.getFieldName();
            String value = uploaded.getString();
            lor.add(new objectresult(key, value));
            if (value == null || value.equals("")) {
                result = true;

            }
        }
    }

    if (result) {
        request.getSession().setAttribute("error", "error");
        String url = "algorithm/addalgo.jsp";
        response.sendRedirect(url);
    } else {
        Algorithm a = new Algorithm(lor.get(0).getValue(), lor.get(1).getValue(), urlf);
        DaoAlgoritm da = new DaoAlgoritm();
        da.create(a);
        a = da.getAlgoritm(a.getNameAlg());
        DaoParameter dp = new DaoParameter();
        for (int i = 3; i < lor.size(); i++) {
            dp.create(new Parameter(a, lor.get(i).getValue(), lor.get(i + 1).getValue()));
            i++;
        }

        request.getSession().setAttribute("algorithm", new DaoAlgoritm().optenerAlgoritmos());
        String url = "algorithm/masteralgo.jsp";
        response.sendRedirect(url);
    }
}

From source file:com.openhr.company.UploadCompLicenseFile.java

@Override
public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();//w  ww  .j  av a  2  s.co  m
        return map.findForward("HRHome");
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);

                // Read the file object contents and parse it and store it in the repos
                FileInputStream fstream = new FileInputStream(storeFile);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;

                //Read File Line By Line
                while ((strLine = br.readLine()) != null) {
                    System.out.print("Processing line - " + strLine);

                    String[] lineColumns = strLine.split(COMMA);

                    if (lineColumns.length < 8) {
                        br.close();
                        in.close();
                        fstream.close();
                        throw new Exception("The required columns are missing in the line - " + strLine);
                    }

                    // Format is - CompID,CompName,Branch,Address,From,To,LicenseKey,FinStartMonth
                    String companyId = lineColumns[0];
                    String companyName = lineColumns[1];
                    String branchName = lineColumns[2];
                    String address = lineColumns[3];
                    String fromDateStr = lineColumns[4];
                    String toDateStr = lineColumns[5];
                    String licenseKey = lineColumns[6];
                    String finStartMonthStr = lineColumns[7];

                    Date fromDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH)
                            .parse(fromDateStr);
                    Date toDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH).parse(toDateStr);
                    address = address.replace(";", ",");

                    List<Company> eComp = CompanyFactory.findByName(companyName);
                    if (eComp == null || eComp.isEmpty()) {
                        Company company = new Company();
                        company.setCompanyId(companyId);
                        company.setName(companyName);
                        company.setFystart(Integer.parseInt(finStartMonthStr));

                        Branch branch = new Branch();
                        branch.setAddress(address);
                        branch.setCompanyId(company);
                        branch.setName(branchName);

                        Licenses license = new Licenses();
                        license.setActive(1);
                        license.setCompanyId(company);
                        license.setFromdate(fromDate);
                        license.setTodate(toDate);
                        license.formLicenseKey();

                        System.out.println("License key formed - " + license.getLicensekey());
                        System.out.println("License key given - " + licenseKey);
                        if (license.getLicensekey().equalsIgnoreCase(licenseKey)) {
                            CompanyFactory.insert(company);
                            BranchFactory.insert(branch);
                            LicenseFactory.insert(license);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("License is tampared. Contact Support.");
                        }
                    } else {
                        // Company is present, so update it.
                        Company company = eComp.get(0);
                        List<Licenses> licenses = LicenseFactory.findByCompanyId(company.getId());

                        Licenses newLicense = new Licenses();
                        newLicense.setActive(1);
                        newLicense.setCompanyId(company);
                        newLicense.setFromdate(fromDate);
                        newLicense.setTodate(toDate);
                        newLicense.formLicenseKey();

                        System.out.println("License key formed - " + newLicense.getLicensekey());
                        System.out.println("License key given - " + licenseKey);

                        if (newLicense.getLicensekey().equalsIgnoreCase(licenseKey)) {
                            for (Licenses lic : licenses) {
                                if (lic.getActive().compareTo(1) == 0) {
                                    lic.setActive(0);
                                    LicenseFactory.update(lic);
                                }
                            }

                            LicenseFactory.insert(newLicense);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("License is tampared. Contact Support.");
                        }
                    }
                }

                //Close the input stream
                br.close();
                in.close();
                fstream.close();
            }
        }
        System.out.println("Upload has been done successfully!");
    } catch (Exception ex) {
        System.out.println("There was an error: " + ex.getMessage());
        ex.printStackTrace();
    }

    return map.findForward("CompLicHome");
}

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/*  w  ww  . j  a  v a  2s.  c o m*/
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String temp_folder = " ";
    try {
        String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;
        temp_folder = dataFolder;
        File uploadD = new File(dataFolder);
        if (!uploadD.exists()) {
            uploadD.mkdir();
        }

        ResultList rs5 = DB.query(
                "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode "
                        + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID="
                        + sectionID);
        rs5.next();

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

        // Sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // creates the directory if it does not exist
        String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/";
        String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester");
        String real_path = temp_folder + File.separator + temp_semester;
        File semester = new File(real_path);

        if (!semester.exists()) {
            semester.mkdir();
        }
        path1 += temp_semester + "/";
        real_path += File.separator;

        String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-"
                + rs5.getString("courseName");
        String real_path1 = real_path + temp_course;
        File course = new File(real_path1);
        if (!course.exists()) {
            course.mkdir();
        }
        path1 += temp_course + "/";
        real_path1 += File.separator;

        String temp_section = "section-" + rs5.getString("sectionNo");
        String real_path2 = real_path1 + temp_section;
        File section = new File(real_path2);
        if (!section.exists()) {
            section.mkdir();
        }
        path1 += temp_section + "/";
        real_path2 += File.separator;
        String sectionPath = path1;

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        if (items != null && items.size() > 0) {
            // iterates over form's fields
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField() && !item.getName().equals("")) {
                    String DBPath = "";
                    System.out.println(item.getName() + " file is for " + item.getFieldName());
                    Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+");
                    int id = field_name.nextInt();
                    fileName = new File(item.getName()).getName();
                    ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id);
                    rs.next();
                    String temp_file = rs.getString("label");
                    String real_path3 = real_path2 + temp_file;
                    File file_type = new File(real_path3);
                    if (!file_type.exists())
                        file_type.mkdir();
                    DBPath = sectionPath + "/" + temp_file + "/";
                    String context_path = DBPath;
                    real_path3 += File.separator;
                    String filePath = real_path3 + fileName;
                    DBPath += fileName;
                    String temp_DBPath = DBPath;

                    int count = 0;
                    File f = new File(filePath);
                    String temp_fileName = f.getName();
                    String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName);
                    String extension = FilenameUtils.getExtension(filePath);
                    String newFullPath = filePath;
                    String tempFileName = " ";

                    while (f.exists()) {
                        ++count;
                        tempFileName = fileNameWithOutExt + "_(" + count + ").";
                        newFullPath = real_path3 + tempFileName + extension;
                        temp_DBPath = context_path + tempFileName + extension;
                        f = new File(newFullPath);
                    }

                    filePath = newFullPath;
                    System.out.println("New path: " + filePath);
                    DBPath = temp_DBPath;
                    String changeFilePath = filePath.replace('/', '\\');
                    String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", "");
                    File uploadedFile = new File(changeFilePath1);
                    System.out.println("Change filepath = " + changeFilePath1);
                    System.out.println("DBPath = " + DBPath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')";
                    DB.update(query);
                    ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id);
                    while (rs3.next()) {
                        String label = rs3.getString("label");
                        out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label
                                + "</a>");
                        out.write("<br><br>");
                    }
                    ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1");
                    rs4.next();
                    String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values("
                            + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")";
                    DB.update(query2);
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    response.sendRedirect(request.getHeader("Referer"));
}

From source file:com.jl.common.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from  ww  w.j a v a  2 s . co  m
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

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

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");//

            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;//

                //
                if (!ExtensionsHandler.isAllowed(resourceType, extension)) {
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                }

                //
                else if (uplFile.getSize() > 50 * 1024) {
                    //
                    ur = new UploadResponse(204);
                }
                // 
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }
    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:manager.doUpdateToy.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w  w . j av a2 s  .  c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();
    String categoryList = "";
    String fileName = null;

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

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    imageFile = new File(item.getName());

                    fileName = name;
                } else {
                    if (item.getFieldName().equals("toyID")) {
                        toyID = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("toyName")) {
                        toyName = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        description = item.getString();
                    }

                    if (item.getFieldName().equals("category")) {
                        categoryList += item.getString();

                    }
                    if (item.getFieldName().equals("secondHand")) {
                        secondHand = item.getString();
                    }

                    if (item.getFieldName().equals("cashpoint")) {
                        cashpoint = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("qty")) {
                        qty = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("discount")) {
                        discount = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("uploadString")) {
                        base64String = item.getString();
                    }
                    //if(item.getFieldName().equals("desc"))
                    // desc= item.getString();
                }
            }
            category = categoryList.split(";");

            //File uploaded successfully
            //request.setAttribute("message", "File Uploaded Successfully" + desc);
        } catch (Exception ex) {

            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    }
    File file = imageFile;
    if (!(fileName == null)) {

        try {
            /*
            * Reading a Image file from file system
             */
            FileInputStream imageInFile = new FileInputStream(file);
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);

            /*
            * Converting Image byte array into Base64 String 
             */
            String imageDataString = encodeImage(imageData);

            request.setAttribute("test", imageDataString);
            /*
            * Converting a Base64 String into Image byte array 
             */
            //byte[] imageByteArray = decodeImage(imageDataString);

            /*
            * Write a image byte array into file system  
             */
            //FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\Mesong\\Pictures\\Screenshots\\30.png");
            //imageOutFile.write(imageByteArray);
            //request.setAttribute("photo", imageDataString);
            // toyDB toydb = new toyDB();
            //Toy t = toydb.listToyByID(1);
            // toydb.updateToy(t.getToyID(), imageDataString, t.getCashpoint(), t.getQTY(), t.getDiscount());

            imageInFile.close();
            //request.getRequestDispatcher("managerPage/result.jsp").forward(request, response);
            //imageOutFile.close();

            imgString = imageDataString;
            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            //out.println("Image not found" + e.getMessage());
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }
    }
    try {
        toyDB toydb = new toyDB();
        // out.println("s");
        //out.println(String.format("%s,%s,%s,%s,%s,%s,%s", toyID, toyName, description, imageDataString, cashpoint, qty, discount));
        if (!base64String.equals(""))
            imgString = base64String;
        toydb.updateToy(toyID, toyName, description, imgString, cashpoint, qty, discount);

        //for(String c : category)
        //   out.println(c);
        //            out.println(toyID);
        //            out.println(description);
        //            out.println(imageDataString);
        //            out.println(cashpoint);
        //            out.println(qty);
        //            out.println(discount);
        toyCategoryDB toyCatdb = new toyCategoryDB();

        toyCatdb.deleteToyType(toyID);

        for (String c : category) {
            toyCatdb.createToyCategory(Integer.parseInt(c), toyID);
        }

        if (!secondHand.equals("")) {
            secondHandDB seconddb = new secondHandDB();

            SecondHand sh = seconddb.searchSecondHand(Integer.parseInt(secondHand));

            int secondHandCashpoint = sh.getCashpoint();
            toydb.updateToySecondHand(toyID, sh.getID());

            toydb.updateToy(toyID, imgString, secondHandCashpoint, qty, discount);
            // out.println("abc");
        } else {
            toydb.updateToySecondHand(toyID, -1);

        }
        //out.println(imgString);
        response.sendRedirect("doSearchToy");
    } catch (Exception e) {
        out.println("sql" + e.getMessage());

    } finally {
        out.close();
    }
}

From source file:massbank.FileUpload.java

/**
 * t@CAbv??[h/*from  w w w .  ja  v a2  s  .com*/
 * multipart/form-datat@CAbv??[h
 * s??nullp
 * @return Abv??[ht@C?MAP<t@C, Abv??[h>
 */
@SuppressWarnings("unchecked")
public HashMap<String, Boolean> doUpload() {

    if (fileItemList == null) {
        try {
            fileItemList = (List<FileItem>) parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return null;
        }
    }

    upFileMap = new HashMap<String, Boolean>();
    for (FileItem fItem : fileItemList) {

        // t@CtB?[h??
        if (!fItem.isFormField()) {

            String key = "";
            boolean val = false;

            // t@C?ipX????j
            String filePath = (fItem.getName() != null) ? fItem.getName() : "";

            // t@C?imt@C?j
            String fileName = (new File(filePath)).getName();
            int pos = fileName.lastIndexOf("\\");
            fileName = fileName.substring(pos + 1);
            pos = fileName.lastIndexOf("/");
            fileName = fileName.substring(pos + 1);

            // t@CAbv??[h
            if (!fileName.equals("")) {
                key = fileName;
                File upFile = new File(outPath + "/" + fileName);
                try {
                    fItem.write(upFile);
                    val = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    upFile.delete();
                }
            }
            upFileMap.put(key, val);
        }
    }

    return upFileMap;
}

From source file:com.controller.UploadLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w .ja v  a  2 s  .co  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();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // 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();
                boolean ch = fi.isFormField();

                if (!fi.isFormField()) {

                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    String uid = (String) getSqlMethodsInstance().session.getAttribute("EmailID");

                    int UID = getSqlMethodsInstance().getUserID(uid);
                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

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

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("UID", UID);
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fi.write(storeFile);

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");
                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}

From source file:com.ephesoft.dcma.gwt.customworkflow.server.ImportPluginUploadServlet.java

/**
 * @param req//w  w  w .j  a v a2 s  .  com
 * @param tempZipFile
 * @param exportSerailizationFolderPath
 * @param printWriter 
 * @return
 */
private File readAndParseAttachedFile(HttpServletRequest req, String exportSerailizationFolderPath,
        PrintWriter printWriter) {
    List<FileItem> items;
    File tempZipFile = null;
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        InputStream instream = null;
        OutputStream out = null;

        items = upload.parseRequest(req);
        for (FileItem item : items) {

            if (!item.isFormField() && IMPORT_FILE.equals(item.getFieldName())) {
                zipFileName = item.getName();
                if (zipFileName != null) {
                    zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
                }
                zipPathname = exportSerailizationFolderPath + File.separator + zipFileName;

                // get only the file name not whole path
                zipPathname = zipFileName;
                if (zipFileName != null) {
                    zipFileName = FilenameUtils.getName(zipFileName);
                }
                try {
                    instream = item.getInputStream();
                    tempZipFile = new File(zipPathname);

                    if (tempZipFile.exists()) {
                        tempZipFile.delete();
                    }
                    out = new FileOutputStream(tempZipFile);
                    byte buf[] = new byte[1024];
                    int len = instream.read(buf);
                    while (len > 0) {
                        out.write(buf, 0, len);
                        len = instream.read(buf);
                    }
                } catch (FileNotFoundException e) {
                    LOG.error("Unable to create the export folder." + e, e);
                    printWriter.write("Unable to create the export folder.Please try again.");

                } catch (IOException e) {
                    LOG.error("Unable to read the file." + e, e);
                    printWriter.write("Unable to read the file.Please try again.");
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException ioe) {
                            LOG.info("Could not close stream for file." + tempZipFile);
                        }
                    }
                    if (instream != null) {
                        try {
                            instream.close();
                        } catch (IOException ioe) {
                            LOG.info("Could not close stream for file." + zipFileName);
                        }
                    }
                }
            }
        }
    } catch (FileUploadException e) {
        LOG.error("Unable to read the form contents." + e, e);
        printWriter.write("Unable to read the form contents.Please try again.");
    }
    return tempZipFile;
}

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

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {//  w ww . j a  v  a  2  s.  c  om
        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(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:com.wwl.utils.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /* ww w  .  ja v  a2  s.  c o  m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());

            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isNotAllowedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                //fileName = UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
                fileName = new Date().getTime() + "." + FilenameUtils.getExtension(fileName);
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}