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

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

Introduction

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

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:com.intranet.intr.clientes.CliControllerFicha.java

@RequestMapping(value = "CProyectoGaleria.htm", method = RequestMethod.POST)
public String ProyectoGaleria_post(@ModelAttribute("fotogaleria") proyecto_certificaciones_galeria galer,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";
    //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosCertificaciones";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);//w  ww  .  ja  v a  2 s .  c  o  m

    ServletFileUpload upload = new ServletFileUpload(factory);
    String ruta = "redirect:CProyectoGaleria.htm?nifC=" + nifC + "&id=" + idP;
    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (idP != 0) {
                galer.setIdPropuesta(idP);
                if (proyectoCertificacionesGaleriaService.existe(item.getName()) == false) {

                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    galer.setNombreimg(item.getName());
                    proyectoCertificacionesGaleriaService.insertar2(galer);
                }
            } else
                ruta = "redirect:CfichaCliente.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return ruta;

}

From source file:com.intranet.intr.contabilidad.SupControllerGastos.java

@RequestMapping(value = "addGastoRF.htm", method = RequestMethod.POST)
public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result,
        HttpServletRequest request) {/*from   ww w.jav a  2 s. c  o  m*/
    String mensaje = "";
    String ruta = "redirect:Gastos.htm";
    gastosR gr = new gastosR();
    //MultipartFile multipart = c.getArchivo();
    System.out.println("olaEnviarMAILS");
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas";
    //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
    //String ubicacionArchivo="C:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (idPC != 0) {
                gr.setIdgasto(idPC);
                if (gastosRService.existe(item.getName()) == false) {
                    System.out.println("NOMBRE FOTO: " + item.getName());
                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    gr.setNombreimg(item.getName());
                    gastosRService.insertar(gr);
                }
            } else
                ruta = "redirect:Gastos.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}

From source file:com.Uploader.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*from  w w w . j a  va 2  s.  com*/

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());
            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);
            out.write("File " + fileItem.getName() + " uploaded successfully.");
            out.write("<br>");
            out.write("<a href=\"Uploader?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName()
                    + "</a>");
        }
    } catch (FileUploadException e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    } catch (Exception e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    }
    out.write("</body></html>");
}

From source file:edu.purdue.pivot.skwiki.server.ImageUploaderServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {

    connection = null;/*from  w  ww.j  ava2  s  .  co m*/
    Statement st = null;

    /* read database details from file */
    BufferedReader br;
    current_project_name = "";
    main_database_name = "";

    try {
        br = new BufferedReader(new FileReader(this.getServletContext().getRealPath("/serverConfig.txt")));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            String first = line.substring(0, line.lastIndexOf(':'));
            String last = line.substring(line.lastIndexOf(':') + 1);

            if (first.contains("content_database")) {
                current_project_name = last;
            }

            if (first.contains("owner_database")) {
                main_database_name = last;
            }

            if (first.contains("username")) {
                postgres_name = last;
            }

            if (first.contains("password")) {
                postgres_password = last;
            }

            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }

        //String everything = sb.toString();
        //System.out.println("file: "+everything);
        br.close();

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

    }

    try {
        connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/" + current_project_name,
                "postgres", "fujiko");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String response = "";
    int cont = 0;
    for (FileItem item : sessionFiles) {
        if (false == item.isFormField()) {
            cont++;
            try {
                String uuid = UUID.randomUUID().toString();
                String saveName = uuid + '.' + FilenameUtils.getExtension(item.getName());

                //               String saveName = item.getName();

                //write to database
                File file = new File(saveName);
                item.write(file);

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

                // / Send a customized message to the client.
                response += "File saved as " + file.getAbsolutePath();

                //write filename to database

                String selectStr = "insert into images values (" + "\'" + item.getFieldName() + "\'," + "\'"
                        + file.getAbsolutePath() + "\'" + ")";
                st = connection.createStatement();
                int textReturnCode = st.executeUpdate(selectStr);

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

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

    // / Send your customized message to the client.
    return response;
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

public void doPost(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/* w  w  w  . ja v  a  2 s .  com*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains("."))
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + filename + Ext);
                    fi.write(uploadFile);
                    imgResize(destinationDirectory + "/" + filename + Ext, 100, 100,
                            destinationDirectory + "/" + filename + "_100");
                    imgResize(destinationDirectory + "/" + filename + Ext, 35, 35,
                            destinationDirectory + "/" + filename);

                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }

}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w .  j ava2  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
 */
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.silverpeas.attachment.servlets.DragAndDrop.java

private String saveFileOnDisk(FileItem item, String componentId, String context) throws Exception {
    String fileName = item.getName();
    if (fileName != null) {
        fileName = FilenameUtils.separatorsToSystem(fileName);
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "file = " + fileName);
        String type = FileRepositoryManager.getFileExtension(fileName);
        String physicalName = new Date().getTime() + "." + type;
        File file = new File(AttachmentController.createPath(componentId, context) + physicalName);
        item.write(file);
        return physicalName;
    }/*from  www .  java 2  s  . c  o m*/
    return null;
}

From source file:com.krawler.esp.handlers.genericFileUpload.java

public void doPostCompay(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*w  w  w . j a  va2 s.  c  o m*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains("."))
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                if (fi.getSize() != 0) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + "temp_" + filename + Ext);
                    fi.write(uploadFile);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 0, 0,
                            destinationDirectory + "/original_" + filename, true);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 130, 25,
                            destinationDirectory + "/" + filename, false);
                    //                  imgResize(destinationDirectory + "/" + filename + Ext,
                    //                        0, 0, destinationDirectory + "/original_" + filename);
                    uploadFile.delete();
                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                this.ErrorMsg = "Problem occured while uploading logo";
                logger.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:com.sun.portal.portletcontainer.driver.admin.UploadServlet.java

private String processFileItem(FileItem fi) throws FileUploadException {

    // On some browsers fi.getName() will return the full path to the file
    // the client select this can cause problems
    // so the following is a workaround.
    try {//from   ww w. j  a va  2s  .  co m
        String fileName = fi.getName();
        if (fileName == null || fileName.trim().length() == 0) {
            return null;
        }
        fileName = FilenameUtils.getName(fileName);

        File fNew = File.createTempFile("opc", ".tmp");
        fNew.deleteOnExit();
        fi.write(fNew);

        File finalFileName = new File(fNew.getParent() + File.separator + fileName);
        if (fNew.renameTo(finalFileName)) {
            return finalFileName.getAbsolutePath();
        } else {
            // unable to rename, copy the contents of the file instead
            PortletWarUpdaterUtil.copyFile(fNew, finalFileName, true, false);
            return finalFileName.getAbsolutePath();
        }

    } catch (Exception e) {
        throw new FileUploadException(e.getMessage());
    }
}

From source file:de.betterform.agent.web.servlet.UploadServlet.java

private void uploadFile(HttpServletRequest request, FileItem uploadItem, String relativeUploadPath)
        throws Exception {
    String realPath = WebFactory.getRealPath(".", request.getSession().getServletContext());
    File uploadDirectory = new File(realPath, relativeUploadPath);
    String fileName = uploadItem.getName();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("uploading file '" + fileName + "' to directory '" + uploadDirectory + "'");
    }/*from   w w w . ja v a 2  s .  c o m*/

    File localFile = new File(uploadDirectory.getAbsolutePath(), fileName);

    if (!localFile.getParentFile().exists()) {
        localFile.getParentFile().mkdirs();
    }
    uploadItem.write(localFile);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("file '" + fileName + "' successfully uploaded to directory '" + uploadDirectory + "'");
    }
}