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:hoot.services.ingest.MultipartSerializerTest.java

@Test
@Category(UnitTest.class)
public void TestserializeUploadedFiles() throws Exception {
    //homeFolder + "/upload/" + jobId + "/" + relPath;
    // Create dummy FGDB

    String jobId = "123-456-789-testosm";
    String wkdirpath = homeFolder + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);/*from w ww. ja  v  a 2s .com*/
    org.junit.Assert.assertTrue(workingDir.exists());

    List<FileItem> fileItemsList = new ArrayList<FileItem>();

    FileItemFactory factory = new DiskFileItemFactory(16, null);
    String textFieldName = "textField";

    FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "dummy1.osm");

    String textFieldValue = "0123456789";
    byte[] testFieldValueBytes = textFieldValue.getBytes();

    OutputStream os = item.getOutputStream();
    os.write(testFieldValueBytes);
    os.close();

    File out = new File(wkdirpath + "/buffer.tmp");
    item.write(out);
    fileItemsList.add(item);
    org.junit.Assert.assertTrue(out.exists());

    Map<String, String> uploadedFiles = new HashMap<String, String>();
    Map<String, String> uploadedFilesPaths = new HashMap<String, String>();

    _ms._serializeUploadedFiles(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths, wkdirpath);

    org.junit.Assert.assertEquals("OSM", uploadedFiles.get("dummy1"));
    org.junit.Assert.assertEquals("dummy1.osm", uploadedFilesPaths.get("dummy1"));

    File content = new File(wkdirpath + "/dummy1.osm");
    org.junit.Assert.assertTrue(content.exists());

    FileUtils.forceDelete(workingDir);
}

From source file:com.seer.datacruncher.services.HttpFileUpload.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {//from   www  . j  a  va2 s .c  o m
        FileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);

        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

            if (!item.isFormField()) {
                String fileName = item.getName();

                String str = getServletContext().getRealPath("/");
                fileName = fileName.substring(0, fileName.indexOf(".")) + ".txt";
                File uploadedFile = new File(str + fileName);
                item.write(uploadedFile);

                out.println("<Status>Success: File has been uploaded at " + uploadedFile.getAbsolutePath()
                        + "</Status>");
                out.flush();
                out.close();

                return;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.println("<Status>Failure</Status>");
    out.flush();
    out.close();
}

From source file:com.intranet.intr.proyecto.EmpControllerProyectoGaleriaCertificaciones.java

@RequestMapping(value = "EProyectoGaleria.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);//from   w  w  w.  j  a  v  a  2 s .  co  m

    ServletFileUpload upload = new ServletFileUpload(factory);
    String ruta = "redirect:EProyectoGaleria.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:ELtaClientesProyecto.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.nemesis.admin.UploadServlet.java

/**
 * @param request//from   ww w.  java  2  s .c  om
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    JsonArray json = new JsonArray();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                final String savedFile = UUID.randomUUID().toString() + "." + getSuffix(item.getName());
                File file = new File(request.getServletContext().getRealPath("/") + "uploads/", savedFile);
                item.write(file);
                JsonObject jsono = new JsonObject();
                jsono.addProperty("name", savedFile);
                jsono.addProperty("path", file.getAbsolutePath());
                jsono.addProperty("size", item.getSize());
                json.add(jsono);
                System.out.println(json.toString());
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.write(json.toString());
        writer.close();
    }

}

From source file:com.krawler.spring.hrms.common.hrmsExtApplDocsDAOImpl.java

public void uploadFile(FileItem fi, String destinationDirectory, String fileName) throws ServiceException {
    try {/* www  . j a va 2s .  c om*/
        File destDir = new File(destinationDirectory);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File uploadFile = new File(destinationDirectory + "/" + fileName);
        fi.write(uploadFile);
    } catch (Exception ex) {
        throw ServiceException.FAILURE("documentDAOImpl.uploadFile", ex);
    }

}

From source file:com.intranet.intr.proyecto.SupControllerProyectoGaleriaCertificaciones.java

@RequestMapping(value = "ProyectoGaleria.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 = "E:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);//w w  w.j  av  a2s . co m

    ServletFileUpload upload = new ServletFileUpload(factory);
    String ruta = "redirect:ProyectoGaleria.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:SLtaClientesProyecto.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:edu.caltech.ipac.firefly.server.servlets.WebPlotServlet.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

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

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

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(req);

    Map<String, String> params = new HashMap<String, String>(10);

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            params.put(name, value);//from  ww w.j a v  a  2s.c om
        } else {
            String fieldName = item.getFieldName();
            try {
                File uf = new File(ServerContext.getTempWorkDir(), System.currentTimeMillis() + ".upload");
                item.write(uf);
                params.put(fieldName, uf.getPath());

            } catch (Exception e) {
                sendReturnMsg(res, 500, e.getMessage(), null);
                return;
            }
        }
    }

    //        String result= ServerCommandAccess.doCommand(params);

    //        sendReturnMsg(res, 200, "results", result);

    // test code..
    //        if (doTest) {
    //            MultiPartPostBuilder builder = new MultiPartPostBuilder(
    //                                    "http://localhost:8080/applications/Spitzer/SHA/servlet/Firefly_MultiPartHandler");
    //            builder.addParam("dummy1", "boo1");
    //            builder.addParam("dummy2", "boo2");
    //            builder.addParam("dummy3", "boo3");
    //            for(UploadFileInfo fi : data.getFiles()) {
    //                builder.addFile(fi.getPname(), fi.getFile());
    //            }
    //            StringWriter sw = new StringWriter();
    //            MultiPartPostBuilder.MultiPartRespnse pres = builder.post(sw);
    //            LOG.briefDebug("uploaded status: " + pres.getStatusMsg());
    //            LOG.debug("uploaded response: " + sw.toString());
    //        }
}

From source file:fll.web.schedule.UploadSchedule.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    clearSesionVariables(session);//from   w  w  w . j  a  va 2 s  .  co  m

    final File file = File.createTempFile("fll", null);
    file.deleteOnExit();
    try {
        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        // process file and keep track of filename in session.scheduleFilename
        final FileItem scheduleFileItem = (FileItem) request.getAttribute("scheduleFile");
        if (null == scheduleFileItem || scheduleFileItem.getSize() == 0) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>A file containing a schedule must be specified</p>");
            WebUtils.sendRedirect(application, response, "/admin/index.jsp");
            return;
        } else {
            scheduleFileItem.write(file);
            session.setAttribute("uploadSchedule_file", file);

            WebUtils.sendRedirect(application, response, "/schedule/CheckScheduleExists");
            return;
        }
    } catch (final FileUploadException e) {
        LOGGER.error("There was an error processing the file upload", e);
        throw new FLLRuntimeException("There was an error processing the file upload", e);
    } catch (final Exception e) {
        final String message = "There was an error writing the uploaded file to the filesystem";
        LOGGER.error(message, e);
        throw new FLLRuntimeException(message, e);
    }

}

From source file:com.adobe.epubcheck.web.EpubCheckServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    if (!ServletFileUpload.isMultipartContent(req)) {
        out.println("Invalid request type");
        return;/* ww  w . j  a v a2  s  . c o m*/
    }
    try {
        DiskFileItemFactory itemFac = new DiskFileItemFactory();
        // itemFac.setSizeThreshold(20000000); // bytes
        File repositoryPath = new File("upload");
        repositoryPath.mkdir();
        itemFac.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(itemFac);
        List fileItemList = servletFileUpload.parseRequest(req);
        Iterator list = fileItemList.iterator();
        FileItem book = null;
        while (list.hasNext()) {
            FileItem item = (FileItem) list.next();
            String paramName = item.getFieldName();
            if (paramName.equals("file"))
                book = item;
        }
        if (book == null) {
            out.println("Invalid request: no epub uploaded");
            return;
        }
        File bookFile = File.createTempFile("work", "epub");
        book.write(bookFile);
        EpubCheck epubCheck = new EpubCheck(bookFile, out);
        if (epubCheck.validate())
            out.println("No errors or warnings detected");
        book.delete();
    } catch (Exception e) {
        out.println("Internal Server Error");
        e.printStackTrace(out);
    }
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 *  //  w  w  w .j av  a  2 s  .  c  o m
 *
 * @param path
 * @param ufc
 * @return
 * @throws Exception
 */
public static void uploadMulti(String path, UploadFileCall ufc) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();
        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {
                String name = item.getName();
                String type = item.getContentType();
                if (StringUtils.isNotBlank(name)) {
                    File f = new File(file + File.separator + name);
                    item.write(f);
                    ufc.file(null, f, name, name, type);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}