Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.ephesoft.gxt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from   w  w w  .  j  a va 2 s.c  o m*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        log.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } catch (IOException e) {
                        log.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "unable to upload. please see server logs for more details.");
        }

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

From source file:it.univaq.servlet.Upload_pub.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request// www  .ja  v  a2s.  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {

    HttpSession s = SecurityLayer.checkSession(request);
    if (ServletFileUpload.isMultipartContent(request)) {

        //dichiaro mappe 
        Map pubb = new HashMap();
        Map rist = new HashMap();
        Map key = new HashMap();
        Map files = new HashMap();
        int idristampa = 0;
        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("titolo") && !name.isEmpty() || name.equals("autore") && !name.isEmpty()
                        || name.equals("descrizione") && !name.isEmpty()) {
                    pubb.put(name, value);
                } else if (name.equals("isbn") && !name.isEmpty() || name.equals("editore") && !name.isEmpty()
                        || name.equals("lingua") && !name.isEmpty()
                        || name.equals("numpagine") && !name.isEmpty()) {
                    rist.put(name, value);
                } else if (name.equals("datapub") && !name.isEmpty()) {

                    rist.put(name, value);
                } else if (name.equals("key1") || name.equals("key2") || name.equals("key3")
                        || name.equals("key4")) {
                    key.put(name, value);
                } else
                    return false;

            } // Se si stratta invece di un file
            else {

                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                if (contentType.equals("image/jpeg") && !fileName.isEmpty()) {
                    //li salvo nella mappa
                    files.put("name", fileName);
                    files.put("type", contentType);
                    files.put("size", sizeInBytes);

                    //li scrivo nel db
                    //Database.connect();
                    Database.insertRecord("files", files);
                    //Database.close();
                    ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                    if (!isNull(rs1)) {
                        while (rs1.next()) {
                            rist.put("copertina", rs1.getInt("id"));

                        }
                    }

                    // Posso scriverlo direttamente su filesystem
                    if (true) {
                        File uploadedFile = new File(
                                getServletContext().getInitParameter("uploads.directory") + fileName);
                        // Solo se veramente ho inviato qualcosa
                        if (item.getSize() > 0) {
                            item.write(uploadedFile);
                        }
                    }
                } else if (!fileName.isEmpty()) {
                    files.put("name", fileName);
                    files.put("type", contentType);
                    files.put("size", sizeInBytes);

                    //li scrivo nel db
                    //Database.connect();
                    Database.insertRecord("files", files);
                    //Database.close();
                    ResultSet rs4 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                    if (!isNull(rs4)) {
                        while (rs4.next()) {

                            rist.put("download", rs4.getInt("id"));
                        }
                    }
                    // Posso scriverlo direttamente su filesystem
                    if (true) {
                        File uploadedFile = new File(
                                getServletContext().getInitParameter("uploads.directory") + fileName);
                        // Solo se veramente ho inviato qualcosa
                        if (item.getSize() > 0) {
                            item.write(uploadedFile);
                        }
                    }

                }

            }
        }

        //inserisco dati  nel db
        pubb.put("idutente", s.getAttribute("userid"));
        //    Database.connect();
        //prova incremento campo inserite per utenti piu attivi
        pubb.put("idutente", s.getAttribute("userid"));
        //    Database.connect();
        int userid = (int) s.getAttribute("userid");
        //prova incremento campo inserite per utenti piu attivi

        //    inserisco parole chiave
        Database.simpleupdateRecord("utenti", "inserite=inserite+1", "id=" + userid);

        //    inserisco parole chiave
        Database.insertRecord("keyword", key);
        //seleziono id parole chiave appena inserite
        ResultSet rs2 = Database.selectRecord("keyword",
                "key1='" + key.get("key1") + "'&&" + "key2='" + key.get("key2") + "'&&" + "key3='"
                        + key.get("key3") + "'&&" + "key4='" + key.get("key4") + "'");
        if (!isNull(rs2)) {
            while (rs2.next()) { //e inserisco id keyword nella tab pubblicazione
                pubb.put("keyword", rs2.getInt("id"));
            }
        }
        //inserisco ora la pubblicazione con tutti i dati
        Database.insertRecord("pubblicazione", pubb);
        //seleziono id pubblicazione appena inserita
        ResultSet rs = Database.selectRecord("pubblicazione", "titolo='" + pubb.get("titolo") + "'");
        //e inserisco l'id nella tab ristampa e  tab files
        while (rs.next()) {
            rist.put("idpub", rs.getInt("id"));
        }

        ResultSet rs3 = Database.selectRecord("ristampa", "isbn=" + rist.get("isbn"));
        while (rs3.next()) {
            idristampa = rs3.getInt("id");
        }
        //inserisco dati in tab ristampa
        //    Database.updateRecord("ristampa", rist, "id " +idristampa);
        Database.insertRecord("ristampa", rist);
        //    Database.close();
        //vado alla pagina di corretto inserimento
        //    FreeMarker.process("home.html", pubb, response, getServletContext());
        return true;
    } else
        return false;
}

From source file:com.ephesoft.gxt.admin.server.UploadImageFileServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String batchClassId = null;//  w  w w .  ja  va 2 s  .c  om
    String docName = null;
    String fileName = null;
    String isAdvancedTableInfo = null;
    InputStream instream = null;
    OutputStream out = null;
    PrintWriter printWriter = resp.getWriter();
    if (ServletFileUpload.isMultipartContent(req)) {

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

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(AdminConstants.CHARACTER_ENCODING_UTF8);
        List<FileItem> items;
        BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        String uploadPath = null;
        try {
            items = upload.parseRequest(req);
            if (req.getParameter("isAdvancedTableInfo") != null) {
                isAdvancedTableInfo = req.getParameter("isAdvancedTableInfo").toString();
            }
            batchClassId = req.getParameter("batchClassId");
            docName = req.getParameter("docName");
            log.debug("Executing Servlet for batchClassId" + batchClassId + " docName: " + docName);
            String fileExtension = null;

            for (FileItem item : items) {

                // process only file upload - discard other form item types

                if (!item.isFormField()) {
                    fileName = item.getName();
                    log.debug("Executing Servlet for fileName from item:" + fileName);

                    // Checks for invalid characters present in uploaded filename.
                    fileName = checkFileNameForInvalidChars(fileName);
                    log.debug("FileName of File after removing invalid characters :" + fileName);
                    if (fileName != null) {
                        fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                        fileExtension = fileName.substring(fileName.lastIndexOf(EXTENSION_CHAR) + 1);
                    }
                    instream = item.getInputStream();
                    printWriter.write(fileName);
                    printWriter.write(AdminConstants.PATTERN_DELIMITER);
                }
            }
            if (batchClassId == null || docName == null) {
                log.error(
                        "Error while loading image... Either batchClassId or doc type is null. Batch Class Id :: "
                                + batchClassId + " Doc Type :: " + docName);
                printWriter.write("Error while loading image... Either batchClassId or doc type is null.");
            } else {
                batchClassId = batchClassId.trim();
                docName = docName.trim();
                if (isAdvancedTableInfo != null
                        && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))) {
                    uploadPath = batchSchemaService.getAdvancedTestTableFolderPath(batchClassId, true);
                } else {
                    uploadPath = batchSchemaService.getTestAdvancedKvExtractionFolderPath(batchClassId, true);
                }
                uploadPath += File.separator + docName.trim() + File.separator;
                File uploadFolder = new File(uploadPath);

                if (!uploadFolder.exists()) {
                    try {
                        boolean tempPath = uploadFolder.mkdirs();
                        if (!tempPath) {
                            log.error(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            printWriter.write(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            return;
                        }
                    } catch (Exception e) {
                        log.error("Unable to create the folders in the temp directory.", e);
                        printWriter
                                .write("Unable to create the folders in the temp directory." + e.getMessage());
                        return;
                    }
                }
                uploadPath += File.separator + fileName;
                uploadPath = uploadPath.substring(0, uploadPath.lastIndexOf(EXTENSION_CHAR) + 1)
                        .concat(fileExtension.toLowerCase());
                out = new FileOutputStream(uploadPath);
                byte buf[] = new byte[1024];
                int len;
                while ((len = instream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                ImageProcessService imageProcessService = this.getSingleBeanOfType(ImageProcessService.class);
                int numberOfPages = 0;
                // deleteFiles(uploadFolder,fileName);
                if (fileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) {
                    numberOfPages = PDFUtil.getPDFPageCount(uploadPath);

                    // code to convert pdf into tiff by checking the OS on which the application is running.
                    BatchInstanceThread batchInstanceThread = new BatchInstanceThread();
                    if (null != isAdvancedTableInfo
                            && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))
                            && numberOfPages != 1) {
                        printWriter.write(" MultiPage_error not supported for Advanced Table Extraction.");
                        log.error("MultiPage File not supported for Advanced Table Extraction.");
                    } else {

                        imageProcessService.convertPdfToSinglePagePNGOrTifUsingGSAPI(new File(uploadPath), "",
                                new File(uploadPath), batchInstanceThread, numberOfPages == 1, true, false,
                                batchClassId);
                        String outputParams = ApplicationConfigProperties.getApplicationConfigProperties()
                                .getProperty(GHOSTSCRIPT_PNG_PARAMS);
                        imageProcessService.convertPdfToSinglePagePNGOrTifUsingGSAPI(outputParams,
                                new File(uploadPath), "", new File(uploadPath), batchInstanceThread,
                                numberOfPages == 1, false, false);
                        batchInstanceThread.execute();
                    }
                } else if (fileExtension.equalsIgnoreCase(FileType.TIF.getExtension())
                        || fileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) {
                    numberOfPages = TIFFUtil.getTIFFPageCount(uploadPath);
                    if (null != isAdvancedTableInfo
                            && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))
                            && numberOfPages != 1) {
                        printWriter.write(" MultiPage_error File not supported for Advanced Table Extraction.");
                        log.error("MultiPage File not supported for Advanced Table Extraction.");
                    } else {
                        if (numberOfPages != 1) {
                            BatchInstanceThread batchInstanceThread = new BatchInstanceThread();
                            imageProcessService.convertPdfOrMultiPageTiffToPNGOrTifUsingIM("",
                                    new File(uploadPath), "", new File(uploadPath), batchInstanceThread, false,
                                    false);
                            imageProcessService.convertPdfOrMultiPageTiffToPNGOrTifUsingIM("",
                                    new File(uploadPath), "", new File(uploadPath), batchInstanceThread, false,
                                    true);
                            batchInstanceThread.execute();
                        } else {
                            imageProcessService.generatePNGForImage(new File(uploadPath));
                        }
                    }
                    log.info("Png file created successfully for file: " + uploadPath);
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        } catch (DCMAException e) {
            log.error("Unable to generate PNG." + e, e);
            printWriter.write("Unable to generate PNG.Please try again.");
        } catch (DCMAApplicationException exception) {
            log.error("Unable to upload Multipage file." + exception, exception);
            printWriter.write("Unable to upload Multipage file.");
        } finally {
            if (out != null) {
                out.close();
            }
            if (instream != null) {
                instream.close();
            }
        }
        printWriter.write("file_seperator:" + File.separator);
        printWriter.write("|");
    }
}

From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadXLF(HttpServletRequest p_request, HttpServletResponse p_response)
        throws IOException, FileUploadException, JSONException {
    String securityCode = p_request.getParameter(JSONPN_SECURITY_CODE);
    Account account = accountDAO.getAccountBySecurityCode(securityCode);
    if (account == null) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(JSONPN_STATUS, STATUS_FAILED);
        jsonObj.put(JSONPN_ERROR_MESSAGE, "The security code is incorrect!");
        logger.error("The security code is incorrect -->" + securityCode);
        p_response.getWriter().write(jsonObj.toString());
        return;//from   w  w w. java  2s  . com
    }

    File fileStorage = CommonDAO.getFileStorage();
    File tempDir = CommonDAO.getFolder(fileStorage, FOLDER_TEMP);
    String jobIDStr = "-1";
    File srcFile = null;
    JobBO job = null;
    String errorMsg = null;
    if (ServletFileUpload.isMultipartContent(p_request)) {
        jobIDStr = RandomStringUtils.randomNumeric(10);
        List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory(1024 * 1024, tempDir))
                .parseRequest(p_request);

        for (FileItem item : fileItems) {
            if (item.isFormField()) {
            } else {
                String fileName = item.getName();
                fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                File srcDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator
                        + jobIDStr + File.separator + XLF_SOURCE_FOLDER);
                srcFile = new File(srcDir, fileName);
                try {
                    item.write(srcFile);
                    logger.info("Uploaded File:" + srcFile.getAbsolutePath());
                } catch (Exception e) {
                    logger.error("Upload error with File:" + srcFile.getAbsolutePath(), e);
                }
            }
        }

        // Initial JobBO
        job = new JobBO(jobIDStr, account.getId(), srcFile);
        // Prepare data for MT
        String parseMsg = parseXLF(job, srcFile);
        if (parseMsg == null)
            errorMsg = checkJobData(job);
        else
            errorMsg = parseMsg;
        if (errorMsg == null || errorMsg.trim().length() == 0) {
            // Do MT
            doMachineTranslation(job);
            jobMap.put(job.getJobID(), job);
        } else {
            // Cancel Job
            job = null;
        }
    }

    JSONObject jsonObj = new JSONObject();
    if (job != null) {
        jsonObj.put(JSONPN_JOBID, job.getJobID());
        jsonObj.put(JSONPN_SOURCE_LANGUAGE, job.getSourceLanguage());
        jsonObj.put(JSONPN_TARGET_LANGUAGE, job.getTargetLanguage());
        jsonObj.put("sourceSegmentSize", job.getSourceSegments().length);
        logger.info("Created Job --> " + jsonObj.toString());
    } else {
        jsonObj.put(JSONPN_STATUS, STATUS_FAILED);
        jsonObj.put(JSONPN_ERROR_MESSAGE, errorMsg);
        logger.error("Failed to create Job --> " + jsonObj.toString() + ", file:" + srcFile + ", account:"
                + account.getAccountName());
    }
    p_response.getWriter().write(jsonObj.toString());
}

From source file:UploadDownloadFile.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);// w w w.j a  v  a2  s .  co m
    String filePath;
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    System.out.println("filePath = " + filePath);
    // filePath = "/Users/jhovarie/Desktop/webuploaded/";
    File f = new File(filePath);
    if (!f.exists()) {
        f.mkdirs();
    }

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    //factory.setRepository(new File("c:\\temp"));
    factory.setRepository(new File(filePath));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<a href='" + currenthost + "/UploadDownloadFile/index.html'><< BACK <<</a><br/>");
        String fileName = "";
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }

        out.println("Target Location = " + filePath);
        out.write(
                "<br/><a href=\"UploadDownloadFile?fileName=" + fileName + "\">Download " + fileName + "</a>");
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println("Error in Process " + ex);
    }
}

From source file:co.estampas.servlets.guardarEstampa.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w  ww  .j ava2 s.c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String rutaImg = "NN";
    /*
     SUBIR LA IMAGEN AL SERVIDOR
     */
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(dirUploadFiles, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            subioImagen = true;
                            rutaImg = "estampas/" + nombre;
                            //                response.sendRedirect("uploadsave.jsp");
                        } else {
                            subioImagen = false;
                        }
                    }
                } else {
                    campos.add(item.getString());
                }
            }
        } catch (FileUploadException e) {
            subioImagen = false;
        } catch (Exception e) {
            subioImagen = false;
        }
    }
    if (subioImagen) {
        String nombreImg = campos.get(1);
        processRequest(request, response);
        EstampaCamiseta estampa = new EstampaCamiseta();
        //BUSCO EL ARTISTA QUE VA A GUARDAR LA ESTAMPA
        this.idArtistax = Integer.parseInt(campos.get(0));
        Artista ar = artistaFacade.find(Integer.parseInt(campos.get(0)));
        estampa.setIdArtista(ar);
        //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA
        TamanoEstampa tamEstampa = tamanoEstampaFacade.find(Integer.parseInt(campos.get(4)));
        estampa.setIdTamanoEstampa(tamEstampa);
        //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA
        TemaEstampa temaEstampa = temaEstampaFacade.find(Integer.parseInt(campos.get(2)));
        estampa.setIdTemaEstampa(temaEstampa);
        //ASIGNO EL NOMBRE DE LA ESTAMPA
        estampa.setDescripcion(nombreImg);
        //ASIGNO LA RUTA DE LA IMAGEN QUE CREO
        estampa.setImagenes(rutaImg);
        //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA
        estampa.setUbicacion(campos.get(5));
        //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO
        estampa.setPrecio(campos.get(3));
        //ASIGNO EL ID DEL LUGAR 
        estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5)));
        //GUARDAR LA ESTAMPA
        estampaCamisetaFacade.create(estampa);
    } else {
        System.out.println("Error al subir imagen");
    }
    campos = new ArrayList<>();

    processRequest(request, response);
}

From source file:de.siegmar.securetransfer.controller.SendController.java

/**
 * Process the send form./*from  w ww  .j a v  a2s  . c  o m*/
 */
@PostMapping
public ModelAndView create(final HttpServletRequest req, final RedirectAttributes redirectAttributes)
        throws IOException, FileUploadException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new IllegalStateException("No multipart request!");
    }

    // Create encryptionKey and initialization vector (IV) to encrypt data
    final KeyIv encryptionKey = messageService.newEncryptionKey();

    // secret shared with receiver using the link - not stored in database
    final String linkSecret = messageService.newRandomId();

    final DataBinder binder = initBinder();

    final List<SecretFile> tmpFiles = handleStream(req, encryptionKey, binder);

    final EncryptMessageCommand command = (EncryptMessageCommand) binder.getTarget();
    final BindingResult errors = binder.getBindingResult();

    if (!errors.hasErrors() && command.getMessage() == null && (tmpFiles == null || tmpFiles.isEmpty())) {
        errors.reject(null, "Neither message nor files submitted");
    }

    if (errors.hasErrors()) {
        return new ModelAndView(FORM_SEND_MSG, binder.getBindingResult().getModel());
    }

    final String senderId = messageService.storeMessage(command.getMessage(), tmpFiles, encryptionKey,
            HashCode.fromString(linkSecret).asBytes(), command.getPassword(),
            Instant.now().plus(command.getExpirationDays(), ChronoUnit.DAYS));

    redirectAttributes.addFlashAttribute("messageSent", true).addFlashAttribute("message",
            command.getMessage());

    return new ModelAndView("redirect:/send/" + senderId).addObject("linkSecret", linkSecret);
}

From source file:ai.ilikeplaces.servlets.ServletFileUploads.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request__/*from   w ww .  jav a2  s . c  om*/
 * @param response__
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException      if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__)
        throws ServletException, IOException {
    response__.setContentType("text/html;charset=UTF-8");
    Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"),
            request__.getLocale());
    PrintWriter out = response__.getWriter();

    final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI");

    try {
        fileUpload: {
            if (!isFileUploadPermitted()) {
                errorTemporarilyDisabled(out);
                break fileUpload;
            }
            processSignOn: {
                final HttpSession session = request__.getSession(false);

                if (session == null) {
                    errorNoLogin(out);
                    break fileUpload;
                } else if (session.getAttribute(ServletLogin.HumanUser) == null) {
                    errorNoLogin(out);
                    break processSignOn;
                }

                processRequestType: {
                    @SuppressWarnings("unchecked")
                    final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session
                            .getAttribute(ServletLogin.HumanUser)).getBoundInstance();
                    try {
                        /*Check that we have a file upload request*/
                        final boolean isMultipart = ServletFileUpload.isMultipartContent(request__);
                        if (!isMultipart) {
                            LoggerFactory.getLogger(ServletFileUploads.class.getName()).error(
                                    logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001"));
                            errorNonMultipart(out);

                            break processRequestType;
                        }

                        processRequest: {

                            // Create a new file upload handler
                            final ServletFileUpload upload = new ServletFileUpload();
                            // Parse the request
                            FileItemIterator iter = upload.getItemIterator(request__);
                            boolean persisted = false;

                            loop: {
                                Long locationId = null;
                                String photoDescription = null;
                                String photoName = null;
                                Boolean isPublic = null;
                                Boolean isPrivate = null;
                                boolean fileSaved = false;

                                while (iter.hasNext()) {
                                    FileItemStream item = iter.next();
                                    String name = item.getFieldName();
                                    String absoluteFileSystemFileName = FilePath;

                                    InputStream stream = item.openStream();
                                    @_fix(issue = "Handle no extension files")
                                    String usersFileName = null;
                                    String randomFileName = null;

                                    if (item.isFormField()) {
                                        final String value = Streams.asString(stream);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0002"),
                                                name);
                                        Loggers.DEBUG.debug(
                                                logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0003"),
                                                value);
                                        if (name.equals("locationId")) {
                                            locationId = Long.parseLong(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0004")));
                                        }

                                        if (name.equals("photoDescription")) {
                                            photoDescription = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0005")));
                                        }

                                        if (name.equals("photoName")) {
                                            photoName = value;
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0006")));
                                        }

                                        if (name.equals("isPublic")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPublic = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug((logMsgs.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0008")));

                                        }
                                        if (name.equals("isPrivate")) {
                                            if (!(value.equals("true") || value.equals("false"))) {
                                                throw new IllegalArgumentException(logMsgs.getString(
                                                        "ai.ilikeplaces.servlets.ServletFileUploads.0007")
                                                        + value);
                                            }

                                            isPrivate = Boolean.valueOf(value);
                                            Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName.");

                                        }

                                    }
                                    if ((!item.isFormField())) {
                                        Loggers.DEBUG.debug((logMsgs.getString(
                                                "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name));
                                        Loggers.DEBUG.debug((logMsgs
                                                .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010")
                                                + item.getName()));
                                        // Process the input stream
                                        if (!(item.getName().lastIndexOf(".") > 0)) {
                                            errorFileType(out, item.getName());
                                            break processRequest;
                                        }

                                        usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName()
                                                : item.getName()
                                                        .substring(item.getName().lastIndexOf("\\") + 1));

                                        final String userUploadedFileName = item.getName();

                                        String fileExtension = "error";

                                        if (userUploadedFileName.toLowerCase().endsWith(".jpg")) {
                                            fileExtension = ".jpg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) {
                                            fileExtension = ".jpeg";
                                        } else if (userUploadedFileName.toLowerCase().endsWith(".png")) {
                                            fileExtension = ".png";
                                        } else {
                                            errorFileType(out, gUI.getString(
                                                    "ai.ilikeplaces.servlets.ServletFileUploads.0019"));
                                            break processRequest;
                                        }

                                        randomFileName = getRandomFileName(locationId);

                                        randomFileName += fileExtension;

                                        final File uploadedFile = new File(
                                                absoluteFileSystemFileName += randomFileName);
                                        final FileOutputStream fos = new FileOutputStream(uploadedFile);
                                        while (true) {
                                            final int dataByte = stream.read();
                                            if (dataByte != -1) {
                                                fos.write(dataByte);
                                            } else {
                                                break;
                                            }

                                        }
                                        fos.close();
                                        stream.close();
                                        fileSaved = true;
                                    }

                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011")
                                                    + locationId);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012")
                                                    + fileSaved);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013")
                                                    + photoDescription);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014")
                                                    + photoName);
                                    Loggers.DEBUG.debug(
                                            logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015")
                                                    + isPublic);

                                    if (fileSaved && (photoDescription != null)) {
                                        persistData: {
                                            handlePublicPrivateness: {
                                                if ((isPublic != null) && isPublic && (locationId != null)) {
                                                    Return<PublicPhoto> r = DB
                                                            .getHumanCRUDPublicPhotoLocal(true)
                                                            .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    locationId, absoluteFileSystemFileName,
                                                                    photoName, photoDescription,
                                                                    new String(CDN + randomFileName), 4);
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, logMsgs.getString(
                                                                "ai.ilikeplaces.servlets.ServletFileUploads.0016"));
                                                    } else {
                                                        errorBusy(out);
                                                    }

                                                } else if ((isPrivate != null) && isPrivate) {
                                                    Return<PrivatePhoto> r = DB
                                                            .getHumanCRUDPrivatePhotoLocal(true)
                                                            .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(),
                                                                    absoluteFileSystemFileName, photoName,
                                                                    photoDescription,
                                                                    new String(CDN + randomFileName));
                                                    if (r.returnStatus() == 0) {
                                                        successFileName(out, usersFileName, "private");
                                                    } else {
                                                        errorBusy(out);
                                                    }
                                                } else {
                                                    throw UNSUPPORTED_OPERATION_EXCEPTION;
                                                }
                                            }
                                        }
                                        /*We got what we need from the loop. Lets break it*/

                                        break loop;
                                    }

                                }

                            }
                            if (!persisted) {
                                errorMissingParameters(out);
                                break processRequest;
                            }

                        }

                    } catch (FileUploadException ex) {
                        Loggers.EXCEPTION.error(null, ex);
                        errorBusy(out);
                    }
                }

            }

        }
    } catch (final Throwable t_) {
        Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_);
    }

}

From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java

/**
 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
 *///from   w w  w.  j  av a  2 s  .  c o  m
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Set multipart
    if (ServletFileUpload.isMultipartContent(request)) {
        try {

            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemList = servletFileUpload.parseRequest(request);
            Hashtable<String, FileItem> multipartFields = parseFields(fileItemList);

            this.setMultipartFields(multipartFields);
        } catch (Exception e) {
            ExceptionUtil.evalueException(request, getResourceBundle(request), LOGGER, e);
        }
    }

    String accion = ParamUtil.getString(request, "accion");
    String accionLogin = ParamUtil.getString(request, "a");
    String scrollTop = ParamUtil.getString(request, "scrollTop", null);
    setForward(false);

    if (scrollTop != null) {
        request.setAttribute("scrollTop", scrollTop);
    }

    // Add information to response
    SettingLogic logic = new SettingLogic();
    try {

        setLocale(request);
        addSettings(request);

        String infoApp = logic.findSetting(Settings.SETTING_INFORMATION);

        request.setAttribute("infoApp", infoApp);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

    if (SecurityUtil.consUserRole(request) == -1 && !HomeServlet.CHOOSE_ROL.equals(accion)
            && request.getRemoteUser() != null && !LoginServlet.LOGOFF.equals(accionLogin)
            && !ErrorServlet.ERROR_403.equals(accion)) {

        setRolSession(request, response);
    }

    // Send info plugins
    sendInfoPlugins(request, ValidateUtil.isNullCh(accion, accionLogin));

    // Send notification center data
    if (getUser(request) != null) {

        // List notifications
        JSONArray notifications = new JSONArray();

        // Declare logic
        NotificationLogic notificationLogic = new NotificationLogic();

        try {

            // Logic
            notifications = notificationLogic.findByContact(getUser(request).getContact());
        } catch (Exception e) {
            ExceptionUtil.evalueException(request, getResourceBundle(request), LOGGER, e);
        }

        // Send notifications to client
        request.setAttribute("notificationCenter", notifications.toString());
    }

}

From source file:filter.MultipartRequestFilter.java

/**
 * Parse the given HttpServletRequest. If the request is a multipart request, then all multipart
 * request items will be processed, else the request will be returned unchanged. During the
 * processing of all multipart request items, the name and value of each regular form field will
 * be added to the parameterMap of the HttpServletRequest. The name and File object of each form
 * file field will be added as attribute of the given HttpServletRequest. If a
 * FileUploadException has occurred when the file size has exceeded the maximum file size, then
 * the FileUploadException will be added as attribute value instead of the FileItem object.
 * @param request The HttpServletRequest to be checked and parsed as multipart request.
 * @return The parsed HttpServletRequest.
 * @throws ServletException If parsing of the given HttpServletRequest fails.
 *///ww  w .  j av  a 2  s  .c om
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException {

    // Check if the request is actually a multipart/form-data request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        // If not, then return the request unchanged.
        return request;
    }

    // Prepare the multipart request items.
    // I'd rather call the "FileItem" class "MultipartItem" instead or so. What a stupid name ;)
    List<FileItem> multipartItems = null;

    try {
        // Parse the multipart request items.
        multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        // Note: we could use ServletFileUpload#setFileSizeMax() here, but that would throw a
        // FileUploadException immediately without processing the other fields. So we're
        // checking the file size only if the items are already parsed. See processFileField().
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request: " + e.getMessage());
    }

    // Prepare the request parameter map.
    Map<String, String[]> parameterMap = new HashMap<String, String[]>();

    // Loop through multipart request items.
    for (FileItem multipartItem : multipartItems) {
        if (multipartItem.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            processFormField(multipartItem, parameterMap);
        } else {
            // Process form file field (input type="file").
            processFileField(multipartItem, request);
        }
    }

    // Wrap the request with the parameter map which we just created and return it.
    return wrapRequest(request, parameterMap);
}