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.aptechfpt.controller.InsertSalePerson.java

private String writeFile(FileItem fileItem) {
    if (fileItem.getName() != null) {
        String realPath = getServletContext().getRealPath("/");
        File uploadDir = new File(realPath + "img/user/" + fileItem.getName());
        //                    File file = File.createTempFile("img", ".jpg", uploadDir);
        try {/*from  w  w  w.j  av  a  2  s  .c om*/
            fileItem.write(uploadDir);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "/img/user/" + fileItem.getName();
    } else {
        return "/img/user/user.jpg";
    }
}

From source file:Commands.UploadImageCommand.java

@Override
public String executeCommand(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String forwardToJsp = "uploadImage.jsp";
    HttpSession session = request.getSession(true);
    String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("") + File.separator + "img"
            + File.separator;/*w  ww . jav a2s . com*/

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

            session.setAttribute("errorMsg", multiparts.size());
            if (multiparts.size() > 0) {
                for (FileItem item : multiparts) {
                    if (item != null) {

                        String name = new File(item.getName()).getName();

                        String filename = UPLOAD_DIRECTORY + name;
                        session.setAttribute("errorMsg", filename);
                        File f = new File(filename);
                        if (!item.isFormField()) {
                            item.write(f);
                        }
                    }
                }
            } else {
                session.setAttribute("errorMsg", "No File Choosen");
            }
        } catch (Exception ex) {

        }
    }
    return forwardToJsp;
}

From source file:ju.ehealthservice.images.SaveImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w  w .  ja v a  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/plain");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String ajaxUpdateResult = "";
    try {
        /* TODO output your page here. You may use following sample code. */
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        List<FileItem> items = upload.parseRequest(request);
        String fileName = "";
        for (FileItem item : items) {
            if (item.isFormField()) {
                fileName = item.getString();
            } else {
                String filePath = Constants.IMAGE_REPOSITORY_PATH + fileName + ".jpg";
                File storeFile = new File(filePath);
                metadata.getData(fileName);
                metadata.updateImage(true);
                item.write(storeFile);
            }
        }
        ajaxUpdateResult = "true";
    } catch (FileUploadException ex) {
        ex.printStackTrace();
        ajaxUpdateResult = "false";
    } catch (Exception ex) {
        ex.printStackTrace();
        ajaxUpdateResult = "false";
    }
    out.print(ajaxUpdateResult);
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

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) {
        return;//from   ww w.  j a v a 2  s.com
    }

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

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

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

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

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

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

    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();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

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

}

From source file:com.elasticgrid.rest.ApplicationsResource.java

/**
 * Handle POST requests: provision a new application.
 */// w  ww.  jav a 2 s  .  co m
@Override
public void acceptRepresentation(Representation entity) throws ResourceException {
    super.acceptRepresentation(entity); //To change body of overridden methods use File | Settings | File Templates.
    try {
        StorageEngine storageEngine = storageManager.getPreferredStorageEngine();
        if (MediaType.MULTIPART_ALL.equals(entity.getMediaType(), true)
                || MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(1000240);
                RestletFileUpload upload = new RestletFileUpload(factory);
                List<FileItem> files = upload.parseRequest(getRequest());
                logger.log(Level.INFO, "Found {0} items", files.size());
                for (FileItem fi : files) {
                    if ("oar".equals(fi.getFieldName())) {
                        // download it as a temp file
                        File file = File.createTempFile("elastic-grid", "oar");
                        fi.write(file);
                        // upload it to storage container
                        logger.log(Level.INFO, "Uploading OAR ''{0}'' to {1}'s container ''{2}''",
                                new Object[] { fi.getName(), storageEngine.getStorageName(), dropBucket });
                        Container container = storageEngine.findContainerByName(dropBucket);
                        try {
                            container.uploadStorable(file);
                        } catch (StorageException e) {
                            logger.log(Level.SEVERE,
                                    String.format("Could not upload OAR '%s' to %s's container '%s'",
                                            fi.getName(), storageEngine.getStorageName(), dropBucket),
                                    e);
                            throw new ResourceException(Status.SERVER_ERROR_INSUFFICIENT_STORAGE, e);
                        }
                    }
                }
                // Set the status of the response.
                logger.info("Redirecting to " + getRequest().getOriginalRef());
                getResponse().setLocationRef(getRequest().getOriginalRef().addSegment("??")); // todo: figure out the proper URL
            } catch (FileUploadException e) {
                e.printStackTrace();
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
            }
        } else if (new MediaType("application/oar").equals(entity.getMediaType())) {
            try {
                // extract filename information
                Form form = (Form) getRequest().getAttributes().get("org.restlet.http.headers");
                // upload it to storage container
                String fileName = form.getFirstValue("x-filename");
                logger.log(Level.INFO, "Uploading OAR ''{0}'' to {1}'s container ''{2}''",
                        new Object[] { fileName, storageEngine.getStorageName(), dropBucket });
                Container container = storageEngine.findContainerByName(dropBucket);
                try {
                    container.uploadStorable(fileName, entity.getStream(), "application/oar");
                } catch (StorageException e) {
                    logger.log(Level.SEVERE, String.format("Could not upload OAR '%s' to %s's container '%s'",
                            fileName, storageEngine.getStorageName(), dropBucket), e);
                    throw new ResourceException(Status.SERVER_ERROR_INSUFFICIENT_STORAGE, e);
                }
                // Set the status of the response
                logger.info("Redirecting to " + getRequest().getOriginalRef());
                getResponse().setLocationRef(getRequest().getOriginalRef().addSegment("??")); // todo: figure out the proper URL
            } catch (Exception e) {
                e.printStackTrace();
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
            }
        } else {
            throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
    }
}

From source file:com.mylop.servlet.ImageServlet.java

public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String account = (String) session.getAttribute("userid");
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from  w  w w. j a  v a2  s  .c o m*/
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String[] ext = contentType.split("/");

                    String fileName = UPLOAD_DIRECTORY + File.separator + account + "_Avatar";
                    File file = new File(fileName);

                    item.write(file);
                    String avatarUrl = "http://mylop.tk:8080/Avatar/" + account + "_Avatar";
                    ProfileModel pm = new ProfileModel();
                    Map<String, String> update = new HashMap<String, String>();
                    update.put("avatar", avatarUrl);
                    pm.updateProfile(account, update);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);

}

From source file:Commands.readFileCommand.java

@Override
public String executeCommand(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String UPLOAD_DIRECTORY = "C:\\Users\\USER\\Downloads\\Movies";
    String forwardToJsp = "";
    HttpSession session = request.getSession(true);
    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*w  ww .  jav  a 2 s  .  c  o  m*/
            ArrayList<FileItem> multiparts = (ArrayList<FileItem>) new ServletFileUpload(
                    new DiskFileItemFactory()).parseRequest(request);
            FileItem item = multiparts.get(0);
            if (!item.getName().isEmpty()) {
                String name = new File(item.getName()).getName();
                String filename = UPLOAD_DIRECTORY + File.separator + name;
                File f = new File(filename);
                boolean exists = f.exists();
                //if (!exists) {
                if (!item.isFormField()) {
                    item.write(f);

                    //                        if (fm.readFile(f)) {
                    //                            forwardToJsp = "Movie.jsp";
                    //                            session.setAttribute("filename", filename);
                    //                            session.setAttribute("allGenre", fm.allGenre());
                    //                            session.setAttribute("allMovie", fm.allMovie());
                    //                            session.setAttribute("most", fm.displayMost());
                    //                            session.setAttribute("score", fm.scoreInGroup());
                    //                            session.setAttribute("avgScore", fm.displayAverage());
                    //                            session.setAttribute("scoreOrder", fm.scoreOrder());
                    //                        } else {
                    //                            session.setAttribute("message", "fail to read file");
                    //                        }
                }
                // } else {
                //    session.setAttribute("message", "File already exists");
                //     forwardToJsp = "index.jsp";
                //}
            } else {
                session.setAttribute("message", "No File Choosen");
            }
        } catch (Exception ex) {
            session.setAttribute("message", ex.getMessage() + ex.getClass());
        }
    } else {
        session.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    return forwardToJsp;
}

From source file:controlador.Carga.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww  w  .  java 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();

    DiskFileItemFactory ff = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(ff);

    List items = null;
    File archivo = null;
    try {
        items = sfu.parseRequest(request);
    } catch (FileUploadException ex) {
        out.print(ex.getMessage());
    }
    for (int i = 0; i < items.size(); i++) {

        FileItem item = (FileItem) items.get(i);

        if (!item.isFormField()) {

            //                archivo = new File(this.getServletContext().getRealPath("/datos/") +"/" + item.getName());
            archivo = new File(
                    "/var/lib/openshift/55672e834382ec6dbc00010d/jbossews/webapps/" + item.getName());
            try {
                item.write(archivo);
            } catch (Exception ex) {
                out.print(ex.getMessage());
            }
        }

    }
    out.print("Se subio el archivo" + this.getServletContext().getRealPath("/datos/"));

    CargaInicial cargar;
    try {
        cargar = new CargaInicial();
        String ubicacion = archivo.toString();
        cargar.cargar(ubicacion);
    } catch (MiExcepcion ex) {
        out.print("Ha ocurrido un error de conexin a base de datos.");
    }

}

From source file:Control.HandleAddFoodMenu.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w  .  j ava2s .com*/
 *
 * @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");
    HttpSession session = request.getSession();
    Food temp = new Food();
    try (PrintWriter out = response.getWriter()) {
        LinkedList<String> names = new LinkedList<>();
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();
        String[] tempS = null;
        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        path = Paths.tempPath;

        String name;
        String sepName = Tools.CurrentTime();
        if (ServletFileUpload.isMultipartContent(request)) {
            List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Iterator iter = multiparts.iterator();
            int index = 0;
            tempS = new String[multiparts.size() - 1];
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    names.add(name);
                    String FilePath = path + Paths.foodImagePath + sepName + name;
                    item.write(new File(FilePath));
                } else {
                    String test = item.getFieldName();
                    tempS[index++] = item.getString();
                }
            }
            index = 0;
            temp.categoryid = Integer.parseInt(tempS[index++]);
            temp.ID = tempS[index++];
            temp.name = tempS[index++];
            temp.price = Double.parseDouble(tempS[index++]);
            temp.pieces = Integer.parseInt(tempS[index++]);
            temp.description = tempS[index++];
            temp.restid = Integer.parseInt(tempS[index++]);
            temp.resID = tempS[index++];
            temp.rename = tempS[index++];

        }

        if (Food.checkExisted(temp.ID, temp.name)) {

            response.sendRedirect("./Admin/AddMenu.jsp?index=1" + "&id=" + temp.restid + "&restid=" + temp.resID
                    + "&name=" + temp.rename);
        } else {
            if (Food.addNewFood(temp)) {
                int id = Food.getFoodID(temp.ID);
                boolean flag = true;
                for (String s : names) {
                    if (Image.addImage(s, Paths.foodImagePathStore + sepName + s, id)) {

                    } else {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    response.sendRedirect("./Admin/AddMenu.jsp?index=2" + "&id=" + temp.restid + "&restid="
                            + temp.resID + "&name=" + temp.rename);
                } else {
                    response.sendRedirect("./Admin/AddMenu.jsp?index=4" + "&id=" + temp.restid + "&restid="
                            + temp.resID + "&name=" + temp.rename);
                }

            } else {
                response.sendRedirect("./Admin/AddMenu.jsp?index=3" + "&id=" + temp.restid + "&restid="
                        + temp.resID + "&name=" + temp.rename);
            }
        }

    } catch (Exception e) {
        response.sendRedirect("./Admin/AddMenu.jsp?index=0" + "&id=" + temp.restid + "&restid=" + temp.resID
                + "&name=" + temp.rename);
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.config.xmldtd.FileUploader.java

private File saveTmpFile(List<FileItem> fileItems) throws Exception {

    File file = File.createTempFile("GSDTDUpload", null);

    // Set overall request size constraint
    long uploadTotalSize = 0;
    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            uploadTotalSize += item.getSize();
        }//from ww  w  . j ava  2s  .co m
    }

    for (ProcessStatus status : listeners) {
        status.setTotalSize(uploadTotalSize);
    }

    log.debug("File size: " + uploadTotalSize);

    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            item.write(file);
            setName(getFileName(item.getName()));
        } else {
            fields.put(item.getFieldName(), item.getString("utf-8"));
        }
    }

    for (ProcessStatus status : listeners) {
        status.finished();
    }

    return file;
}