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:edu.caltech.ipac.firefly.server.servlets.FitsUpload.java

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

    File dir = ServerContext.getVisUploadDir();
    File uploadedFile = getUniqueName(dir);

    String overrideKey = req.getParameter("cacheKey");

    DiskFileItemFactory factory = new DiskFileItemFactory();

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

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

    // Process the uploaded items
    Iterator iter = items.iterator();
    FileItem item = null;
    if (iter.hasNext()) {
        item = (FileItem) iter.next();/*from   w  w  w . j a v a2 s .  co m*/

        if (!item.isFormField()) {
            try {
                item.write(uploadedFile);
            } catch (Exception e) {
                sendReturnMsg(res, 500, e.getMessage(), null);
                return;
            }

        }
    }

    if (item == null) {
        sendReturnMsg(res, 500, "Could not find a upload file", null);
        return;
    }

    if (FileUtil.isGZipFile(uploadedFile)) {
        File uploadedFileZiped = new File(uploadedFile.getPath() + "." + FileUtil.GZ);
        uploadedFile.renameTo(uploadedFileZiped);
        FileUtil.gUnzipFile(uploadedFileZiped, uploadedFile, (int) FileUtil.MEG);
    }

    PrintWriter resultOut = res.getWriter();
    String retFile = ServerContext.replaceWithPrefix(uploadedFile);
    UploadFileInfo fi = new UploadFileInfo(retFile, uploadedFile, item.getName(), item.getContentType());
    String fileCacheKey = overrideKey != null ? overrideKey : retFile;
    UserCache.getInstance().put(new StringKey(fileCacheKey), fi);
    resultOut.println(fileCacheKey);
    String size = StringUtils.getSizeAsString(uploadedFile.length(), true);
    Logger.info("Successfully uploaded file: " + uploadedFile.getPath(), "Size: " + size);
    Logger.stats(Logger.VIS_LOGGER, "Fits Upload", "fsize", (double) uploadedFile.length() / StringUtils.MEG,
            "bytes", size);
}

From source file:com.controller.ChangeImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//  w w w.  java  2s  .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 doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if it is multipart content
    String path = "";
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    path = UPLOAD_DIRECTORY + File.separator + name;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    response.setContentType("text/plain");
    response.getWriter().write(path);
}

From source file:jeeves.server.sources.JeevletServiceRequestFactory.java

private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception {

    Element params = new Element("params");

    // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ...
    // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

    // The Apache FileUpload project parses HTTP requests which
    // conform to RFC 1867, "Form-based File Upload in HTML". That
    // is, if an HTTP request is submitted using the POST method,
    // and with a content type of "multipart/form-data", then
    // FileUpload can parse that request, and get all uploaded files
    // as FileItem.

    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240); // en mmoire
    factory.setRepository(new File(uploadDir));

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    upload.setFileSizeMax(maxUploadSize * 1024 * 1024);

    List<FileItem> items;/*from  w ww.jav  a  2 s.c o m*/
    try {
        items = upload.parseRequest(req);// parseRepresentation(req.getEntity());

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem item = (FileItem) it.next();

            String name = item.getFieldName();

            if (item.isFormField())
                params.addContent(new Element(name).setText(item.getString()));
            else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();
                Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // throw jeeves exception --> reached code ? see apache docs -
        // FileUploadBase
        throw new FileUploadTooBigEx();
    } catch (FileUploadException e) {
        // Sample Restlet ... " 

        // The message of all thrown exception is sent back to client as simple plain text
        // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN));
        // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        // e.printStackTrace();

        // " ... now throw a JeevletException but
        // FIXME must throw Exception with a correct Status
        throw new JeevletException(e);
    }

    return params;
}

From source file:hu.sztaki.lpds.storage.net.bes.FileUploadServlet.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//from   ww w.  j  a v  a2s  . c o m
 * @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");
    ServletRequestContext servletRequestContext = new ServletRequestContext(request);
    boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext);
    if (isMultipart) {
        File newFile;
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        servletFileUpload.setSizeMax(Long.MAX_VALUE);
        try {
            List<FileItem> listFileItems = servletFileUpload.parseRequest(request);
            String path = PropertyLoader.getInstance().getProperty("portal.prefix.dir") + "storage/"
                    + request.getParameter("path") + "/";
            String link = request.getParameter("link");
            File f = new File(path);
            f.mkdirs();

            String[] pathData = request.getParameter("path").split("/");
            for (FileItem t : listFileItems) {
                if (!t.isFormField()) {
                    newFile = new File(path + "/" + t.getFieldName());
                    t.write(newFile);
                    QuotaService.getInstance().addPlussRtIDQuotaSize(pathData[0], pathData[1], pathData[2],
                            pathData[5], newFile.length());
                    //                        QuotaService.getInstance().get(pathData[0], pathData[1]).g
                    //                        System.out.println("STORAGE:"+newFile.getAbsolutePath());
                    if (link != null)
                        if (!t.getFieldName().equals(link))
                            FileUtils.getInstance().createLink(path, t.getFieldName(),
                                    path + link + getGeneratorPostFix(t.getFieldName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:com.krawler.esp.servlets.fileUploadXLS.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//from w  w  w. ja va 2  s  . c  o  m
 * @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");
    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();
    try {
        jobj.put("success", true);
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10000000);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        String destinationDirectory = StorageHandler.GetDocStorePath() + "xlsfiles";
        String fileName = null;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField())
                continue;
            fileName = fi.getName();

            fi.write(new File(destinationDirectory, fileName));
        }

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(destinationDirectory + "/" + fileName));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        int count = wb.getNumberOfSheets();
        JSONArray jArr = new JSONArray();
        for (int x = 0; x < count; x++) {
            JSONObject obj = new JSONObject();
            obj.put("name", wb.getSheetName(x));
            obj.put("index", x);
            jArr.put(obj);
        }
        jobj.put("file", destinationDirectory + "/" + fileName);
        jobj.put("data", jArr);
        jobj.put("msg", "Image has been successfully uploaded");
        jobj.put("lsuccess", true);
        jobj.put("valid", true);
    } catch (Exception e) {
        Logger.getLogger(fileUploadXLS.class.getName()).log(Level.SEVERE, null, e);
        try {
            jobj.put("msg", e.getMessage());
            jobj.put("lsuccess", false);
            jobj.put("valid", true);
        } catch (Exception ex) {
        }
    } finally {
        out.println(jobj);
    }
}

From source file:eg.nileu.cis.nilestore.webapp.servlets.UploadServletRequest.java

/**
 * Init_ajax upload.//from  w  w  w. j a  v a2  s .  c  o m
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
private void init_ajaxUpload() throws Exception {

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = uploadHandler.parseRequest(request);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            File f = File.createTempFile("upfile", ".tmp");
            f.deleteOnExit();
            item.write(f);
            fileName = item.getName();
            if (fileName.contains(File.separator)) {
                fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
            }
            filePath = f.getAbsolutePath();
            isFileFound = true;
            // Here we handle only one file at once
            break;
        } else {
            if (item.getFieldName().equals(DEST_FIELD_NAME)) {
                dest = Integer.valueOf(item.getString());
            }
        }
    }
    String t = getParameter("t");
    if (t != null) {
        returnType = t;
    }
}

From source file:Index.UploadFileServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w . j  a v a  2 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 {
    response.setContentType("text/html;charset=UTF-8");

    String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\NetBeansProjects\\QuickOrderWeb\\web\\images";

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);
    factory.setRepository(new File(ubicacionArchivo));

    ServletFileUpload upload = new ServletFileUpload(factory);

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

        for (FileItem item : partes) {
            File file = new File(ubicacionArchivo,
                    request.getSession().getAttribute("userName").toString() + ".jpg");
            item.write(file);
            System.out.println("name: " + item.getName());
        }
        request.setAttribute("error", null);
        request.setAttribute("result", "Se ha registrado correctamente");
        request.setAttribute("funcionalidad", "Imagen");
        request.getSession().removeAttribute("userName");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    } catch (FileUploadException ex) {
        System.out.println("Error al subir el archivo: " + ex.getMessage());

        request.setAttribute("error", "Error al subir la imagen");
        request.setAttribute("funcionalidad", "Imagen");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    } catch (Exception ex) {
        System.out.println("Error al subir el archivo: " + ex.getMessage());
        request.setAttribute("error", "Error al subir la imagen");
        request.setAttribute("funcionalidad", "Imagen");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);

    }

}

From source file:net.daw.control.upload.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("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String name = "";
        String strMessage = "";
        HashMap<String, String> hash = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(".//..//webapps//images//" + name));
                    } else {
                        hash.put(item.getFieldName(), item.getString());
                    }
                }
                Gson oGson = new Gson();
                Map<String, String> data = new HashMap<>();
                Iterator it = hash.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry e = (Map.Entry) it.next();
                    data.put(e.getKey().toString(), e.getValue().toString());
                }
                data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/images/" + name);
                out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}");
            } catch (Exception ex) {
                strMessage += "File Upload Failed: " + ex;
                out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
            }
        } else {
            strMessage += "Only serve file upload requests";
            out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
        }
    }
}

From source file:com.app.uploads.ImageTest.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/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String type = "";
    CallableStatement pro;

    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        type = new String(b);
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT_TEST(?,?)}");
                pro.setInt(1, 2);
                pro.setString(2, name);
                pro.executeQuery();
                pro.close();
                connect.close();
                if (name != null) {
                    request.setAttribute("type", type);
                    request.setAttribute("success", "ok");
                }
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher("/SearchEngine.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

From source file:com.app.uploads.ImageUploads.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  ww .  jav a 2  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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String[] Fielname = new String[2];
    CallableStatement pro;
    int i = 0;
    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        if (i == 0) {
                            Fielname[0] = new String(b);
                        } else {
                            Fielname[1] = new String(b);
                        }
                        i++;
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT(?,?,?)}");
                pro.setString(1, name);
                pro.setString(2, Fielname[0]);
                pro.setString(3, Fielname[1]);
                pro.executeQuery();
                pro.close();
                connect.close();
                request.setAttribute("message", "File Uploaded Successfully");
                request.setAttribute("name", name);
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
        out.print("Description:" + Fielname[0]);
        out.print("Locator:" + Fielname[1]);
        String pathReal = getServletContext().getRealPath("\\uploads\\");
        request.setAttribute("Description", Fielname[0]);
        request.setAttribute("Locator", Fielname[1]);
        request.setAttribute("path", pathReal);
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    } finally {
        out.close();
    }
}