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:controller.CreateProduct.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w  w  .  j  a  va  2 s  . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    MultipartRequest mr = new MultipartRequest(request,
            "C:/Users/Randy/Documents/NetBeansProjects/Override/web/imagesProducts/");
    try {
        //Clases
        model.business.Producto p = new model.business.Producto();
        model.dal.ProductoDal productoDal = new ProductoDal();

        //Se usa este Request cuando se tiene  enctype="multipart/form-data" (Importar JAR)

        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */
        List items = servlet_up.parseRequest(request);

        for (int i = 0; i < items.size(); i++) {
            /*FileItem representa un archivo en memoria que puede ser pasado al disco duro*/
            FileItem item = (FileItem) items.get(i);
            /*item.isFormField() false=input file; true=text field*/
            if (!item.isFormField()) {
                /*cual sera la ruta al archivo en el servidor*/

                File archivo_server = new File(
                        "C:/Users/Randy/Documents/NetBeansProjects/Override/web/imagesProducts/"
                                + item.getName());
                /*y lo escribimos en el servido*/
                item.write(archivo_server);
            }
        }

        //Set
        p.setIdProducto(Integer.parseInt(mr.getParameter("txt_id_producto")));
        p.setNombreProducto(mr.getParameter("txt_nombre_producto"));
        p.setPrecioUnitario(Integer.parseInt(mr.getParameter("txt_precio")));
        p.setStock(Integer.parseInt(mr.getParameter("txt_stock")));
        p.setDescripcion(mr.getParameter("txt_descripcion"));
        p.getTipoProducto().setIdTipoProducto(Integer.parseInt(mr.getParameter("ddl_lista_tipo_producto")));
        p.getMarca().setIdMarca(Integer.parseInt(mr.getParameter("ddl_marca_producto")));
        //Recoge el NOMBRE del file
        p.setUrlFoto(mr.getFilesystemName("file"));
        p.setEstado(Integer.parseInt(mr.getParameter("rbtn_estado")));

        //Registro BD
        int resultado = productoDal.insertProduct(p);
        switch (resultado) {
        case 1:
            //out.print("Registro OK");
            //Pagina Redirrecion
            request.getRequestDispatcher("redirect_index_intranet_producto_creado.jsp").forward(request,
                    response);
            break;
        case 1062:
            //out.print("Producto Existente");
            //Pagina Redirrecion
            request.getRequestDispatcher("redirect_index_intranet_error_producto_existente.jsp")
                    .forward(request, response);
            break;
        default:
            //Error genrico
            request.getRequestDispatcher("redirect_index_intranet_error.jsp").forward(request, response);
            //out.print("Error : "+ productoDal.insertProduct(p));
            //Pagina Redirrecion
            //request.getRequestDispatcher("pagina.jsp").forward(request, response);
            break;
        }

    } catch (Exception e) {
        //Error genrico
        request.getRequestDispatcher("redirect_index_intranet_error.jsp").forward(request, response);
        //out.print("error : " + e.getMessage());
    }
}

From source file:graphvis.webui.servlets.UploadServlet.java

/**
  * This method receives POST from the index.jsp page and uploads file, 
  * converts into the correct format then places in the HDFS.
  *///from w w w  .j ava2 s.  c o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        response.setStatus(403);
        return;
    }

    File tempDirFileObject = new File(Configuration.tempDirectory);

    // Create/remove temp folder
    if (tempDirFileObject.exists()) {
        FileUtils.deleteDirectory(tempDirFileObject);
    }

    // (Re-)create temp directory
    tempDirFileObject.mkdir();
    FileUtils.copyFile(
            new File(getServletContext()
                    .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")),
            new File(Configuration.tempDirectory
                    + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar"));
    FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")),
            new File(Configuration.tempDirectory + "/dist-graphvis.jar"));

    // 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(Configuration.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")));

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

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

    String fileName = "";
    try {
        // Parse the request
        List<?> items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                String filePath = Configuration.tempDirectory + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    throw new ServletException(ex);
                }
            }
        }

        String fullFilePath = Configuration.tempDirectory + File.separator + fileName;

        String extension = FilenameUtils.getExtension(fullFilePath);

        // Load Files intoHDFS
        // (This is where we do the parsing.)
        loadIntoHDFS(fullFilePath, extension);

        getServletContext().setAttribute("fileName", new File(fullFilePath).getName());
        getServletContext().setAttribute("fileExtension", extension);

        // Displays fileUploaded.jsp page after upload finished
        getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    }

}

From source file:cc.kune.core.server.manager.file.FileUploadManager.java

/**
 * Creates the uploaded file wrapped./*from  w ww . j a  v  a2  s . com*/
 * 
 * @param userHash
 *          the user hash
 * @param stateToken
 *          the state token
 * @param fileName
 *          the file name
 * @param fileUploadItem
 *          the file upload item
 * @param typeId
 *          the type id
 * @return the content
 * @throws Exception
 *           the exception
 */
@Authenticated
@Authorizated(accessRolRequired = AccessRol.Editor, actionLevel = ActionLevel.container, mustCheckMembership = false)
@KuneTransactional
Content createUploadedFileWrapped(final String userHash, final StateToken stateToken, final String fileName,
        final FileItem fileUploadItem, final String typeId) throws Exception {
    final String relDir = FileUtils.toDir(stateToken);
    final String absDir = kuneProperties.get(KuneProperties.UPLOAD_LOCATION) + relDir;
    fileManager.mkdir(absDir);

    File file = null;
    try {
        final String filenameUTF8 = new String(fileName.getBytes(), UTF8);
        file = fileManager.createFileWithSequentialName(absDir, filenameUTF8);
        fileUploadItem.write(file);

        final String mimetype = fileUploadItem.getContentType();
        final BasicMimeType basicMimeType = new BasicMimeType(mimetype);
        LOG.info("Mimetype: " + basicMimeType);
        final String extension = FileUtils.getFileNameExtension(file.getName(), false);

        String preview = "";

        if (basicMimeType.isImage()) {
            generateThumbs(absDir, file.getName(), extension, false);
        } else if (basicMimeType.isPdf()) {
            generateThumbs(absDir, file.getName(), "png", true);
        } else if (basicMimeType.isText()) {
            final String textPreview = new String(FileUtils.getBytesFromFile(file));
            preview = "<pre>" + StringW.wordWrap(textPreview) + "</pre>";
        }

        // Persist
        final User user = userSession.getUser();
        final Container container = accessService
                .accessToContainer(ContentUtils.parseId(stateToken.getFolder()), user, AccessRol.Editor);
        final Content content = creationService.createContent(
                FileUtils.getFileNameWithoutExtension(file.getName(), extension), preview, user, container,
                typeId);
        content.setMimeType(basicMimeType);
        content.setFilename(file.getName());
        return content;
    } catch (final Exception e) {
        if (file != null && file.exists()) {
            logFileDel(file.delete());
        }
        throw e;
    }
}

From source file:com.stratelia.webactiv.servlets.FileUploader.java

private void processAttachment(String fileId, String userId, FileItem file, String language) throws Exception {
    SilverTrace.debug("peasUtil", "FileUploader.processAttachment()", "root.MSG_GEN_ENTER_METHOD",
            "fileId = " + fileId);
    AttachmentDetail attachmentDetail = AttachmentController.searchAttachmentByPK(new AttachmentPK(fileId));
    String componentId = attachmentDetail.getInstanceId();
    String destFile = FileRepositoryManager.getAbsolutePath(componentId)
            + AttachmentController.CONTEXT_ATTACHMENTS + attachmentDetail.getPhysicalName(language);
    File uploadFile = new File(destFile);
    file.write(uploadFile);
    AttachmentController.checkinFile(fileId, userId, true, false, true, language);
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

private void processUploadFile(FileItem item, PrintWriter pw) throws Exception {
    String filename = item.getName();
    System.out.println(filename);
    int index = filename.lastIndexOf("\\");
    filename = filename.substring(index + 1, filename.length());

    long fileSize = item.getSize();

    if ("".equals(filename) && fileSize == 0) {
        throw new RuntimeException("You didn't upload a file.");
        //return;
    }//ww w .ja  v  a  2 s . c om

    File uploadFile = new File(filePath + "/" + filename);
    item.write(uploadFile);
    pw.println("<a id=\"filelink\" href=\"" + prefix_url + filename + "\" >Link</a> to the uploaded file : "
            + filename);
    System.out.println(fileSize + "\r\n");
}

From source file:com.sa.osgi.jetty.UploadServlet.java

private void processUploadedFile(FileItem item) {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    System.out.println("file name: " + fileName);
    try {//from   ww w  .  j ava 2 s  .  c o  m
        //            InputStream inputStream = item.getInputStream();
        //            FileOutputStream fout = new FileOutputStream("/tmp/aa");
        //            fout.write(inputStream.rea);
        String newFileName = "/tmp/" + fileName;
        item.write(new File(newFileName));
        ServiceFactory factory = ServiceFactory.INSTANCE;
        MaoService maoService = factory.getMaoService();
        boolean b = maoService.installBundle(newFileName);
        System.out.println("Installation Result: " + b);

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

From source file:com.intranet.intr.inbox.SupControllerInbox.java

@RequestMapping(value = "enviarMailA.htm", method = RequestMethod.POST)
public String enviarMailA_post(@ModelAttribute("correo") correoNoLeidos c, BindingResult result,
        HttpServletRequest request) {//  ww w .j a v  a  2s  . co m
    String mensaje = "";

    try {
        //MultipartFile multipart = c.getArchivo();
        System.out.println("olaEnviarMAILS");
        String ubicacionArchivo = "C:\\DecorakiaReportesIntranet\\archivosMail\\";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

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

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            arc.add(item.getName());
            System.out.println("img" + item.getName());
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:enviarMail.htm";

}

From source file:br.edu.ifpb.ads.psd.projeto.servlets.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w  w  . j  a va  2  s  . c  om*/
 * @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 {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciadorDeUsuario gerenciarUsuario = new GerenciadorDeUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario);
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}

From source file:com.br.ifpb.servlet.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w  w .j ava2s.c  om*/
 * @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 {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarUsuario gerenciarUsuario = new GerenciarUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            Timestamp.valueOf(LocalDateTime.now()), usuario);
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}

From source file:com.naval.persistencia.hibernate.SubirArchivo.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// ww  w  . j  av a  2  s  .co 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 idSolicitud = request.getParameter("idSolicitud");
    String accion = request.getParameter("accion");
    if (accion != null && "editarSolicitud".equals(accion)) {
        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
        PrintWriter writer = response.getWriter();

        List<FileItem> items;
        try {
            items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {

                    FileItem actual = null;
                    actual = item;
                    String fileName = actual.getName();

                    String str = request.getSession().getServletContext().getRealPath("/adjuntos/");
                    fileName = idSolicitud + "-" + fileName;
                    // nos quedamos solo con el nombre y descartamos el path
                    File fichero = new File(str + "\\" + fileName);

                    try {
                        actual.write(fichero);
                        String aux = "{" + "\"name\":\"" + fichero.getName() + "\",\"size\":\"" + 2000
                                + "\",\"url\":\"/adjuntos/" + fichero.getName()
                                + "\",\"thumbnailUrl\":\"/thumbnails/" + fichero.getName()
                                + "\",\"deleteUrl\":\"/Subir?file=" + fichero.getName()
                                + "\",\"deleteType\":\"DELETE" + "\",\"type\":\"" + fichero.getName() + "\"}";

                        writer.write("{\"files\":[" + aux + "]}");
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception ex) {
        }

    } else {
        processRequest(request, response);
    }

}