Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

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  w ww. j  a va  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: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  w w  .  j a  v  a  2s. co  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:com.news.util.UploadFileUtil.java

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;//from ww w  .  j  a v a 2  s  .  c  om
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "";
    ///opt/apache-tomcat-7.0.59/webapps/noithat
    //filePath = getServletContext().getRealPath("") + File.separator + "test-upload" + File.separator;
    filePath = File.separator + File.separator + "opt" + File.separator + File.separator;
    filePath += "apache-tomcat-7.0.59" + File.separator + File.separator + "webapps";
    filePath += File.separator + File.separator + "noithat";
    filePath += File.separator + File.separator + "upload" + File.separator + File.separator;
    filePath += "images" + File.separator;

    //filePath = "E:" + File.separator;

    // Verify the content type
    String contentType = request.getContentType();
    System.out.println("contentType=" + contentType);
    if (contentType != null && (contentType.indexOf("multipart/form-data") >= 0)) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("c:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);
        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);
            System.out.println("fileItems.size()=" + fileItems.size());
            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField() && fi.getFieldName().equals(paramName)) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    int dotPos = fi.getName().lastIndexOf(".");
                    if (dotPos < 0) {
                        fileName += ".jpg";
                    } else {
                        fileName += fi.getName().substring(dotPos);
                    }
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    fi.write(file);
                    System.out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                    result = fileName;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:hirondelle.situris.main.centrosInteresse.FileUploadWrapper.java

/** Constructor.  */
public FileUploadWrapper(HttpServletRequest aRequest) throws IOException {
    super(aRequest);
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    try {//w ww  . j  av a2  s  .com
        List<FileItem> fileItems = upload.parseRequest(aRequest);
        convertToMaps(fileItems);
    } catch (FileUploadException ex) {
        throw new IOException("Cannot parse underlying request: " + ex.toString());
    }
}

From source file:com.certus.actions.uploadSliderImageAction.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = getServletContext().getRealPath("img/slider").replace("build/", "");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from   w ww  . j ava  2s. c  o m*/
            List<FileItem> multiparts = upload.parseRequest(request);
            StringBuilder sb = null;
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    double randomA = Math.random() * 1000000000;
                    int randA = (int) randomA;
                    String name = new File(item.getName()).getName();
                    sb = new StringBuilder(name);
                    sb.replace(0, name.length() - 4, "slider-" + randA);
                    item.write(new File(path + File.separator + sb));
                }
            }
            String pathTo = path + File.separator + sb;
            response.getWriter().write(pathTo.substring(pathTo.lastIndexOf("img")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;/* w  w  w . j  a  v a2s  . com*/
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:br.com.sislivros.servlets.RecDadosCometGroup.java

protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/html;charset=UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;/*from   w w  w.  j av  a 2 s. co  m*/
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    req.setAttribute(item.getFieldName(), item.getString());
                    //                  resp.getWriter().println("No  campo file"+ this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());

                } else {
                    //caso seja um campo do tipo file

                    //                  resp.getWriter().println("Valor do Campo: ");
                    //                  resp.getWriter().println("Campo file");
                    //                  resp.getWriter().println("Name:"+item.getFieldName());
                    //                  resp.getWriter().println("nome arquivo: "+item.getName());
                    //                  resp.getWriter().println("Size:"+item.getSize());
                    //                  resp.getWriter().println("ContentType:"+item.getContentType());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "";
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                        resp.getWriter().println("Caminho: " + caminho);
                        //                          File uploadedFile = new File("C:\\TomCat\\apache-tomcat-8.0.21\\webapps\\sislivros\\" + caminho);
                        File uploadedFile = new File(
                                "E:\\Documentos\\NetBeansProjects\\sislivrosgit\\sisLivro\\build\\web\\"
                                        + caminho);
                        item.write(uploadedFile);
                    }

                    req.setAttribute("caminho", caminho);
                    //                        req.setAttribute("param", req.getParameter("comment-add"));
                    req.getRequestDispatcher("editarGrupo").forward(req, resp);
                }

            }

        } catch (Exception e) {
            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }
}

From source file:Atualizar.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;/*from w w  w .j  a va2 s.co  m*/
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    resp.getWriter()
                            .println("No  campo file" + this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());
                    req.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file

                    resp.getWriter().println("Campo file");
                    resp.getWriter().println("Name:" + item.getFieldName());
                    resp.getWriter().println("nome arquivo :" + item.getName());
                    resp.getWriter().println("Size:" + item.getSize());
                    resp.getWriter().println("ContentType:" + item.getContentType());
                    resp.getWriter().println(
                            "C:\\uploads" + File.separator + new Date().getTime() + "_" + item.getName());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = this.getServletContext().getRealPath("\\img\\user.jpg");
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                    }

                    resp.getWriter().println("Caminho: " + caminho);
                    req.setAttribute("caminho", caminho);
                    File uploadedFile = new File(
                            "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho);
                    item.write(uploadedFile);
                    req.setAttribute("caminho", caminho);
                    //                                                req.getRequestDispatcher("cadastrouser").forward(req, resp);
                }
            }
        } catch (Exception e) {
            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }

}

From source file:com.epam.wilma.webapp.config.servlet.stub.upload.helper.ServletFileUploadFactory.java

/**
 * Creates a new {@link ServletFileUpload} instance.
 * @return with the new instance.//from ww  w  .  ja  v a2s .co m
 */
public ServletFileUpload createInstance() {
    FileItemFactory factory = new DiskFileItemFactory();
    return new ServletFileUpload(factory);
}

From source file:AtualizarUser.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;//from   ww  w .  ja v a 2s . c  om
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //                                            items.get(0).getString();
                    req.setAttribute(item.getFieldName(), item.getString());
                    resp.getWriter()
                            .println("No  campo file" + this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());

                    req.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file

                    resp.getWriter().println("Campo file");
                    resp.getWriter().println("Name:" + item.getFieldName());
                    resp.getWriter().println("nome arquivo :" + item.getName());
                    resp.getWriter().println("Size:" + item.getSize());
                    resp.getWriter().println("ContentType:" + item.getContentType());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "img\\usuario.jpg";
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                        resp.getWriter().println("Caminho: " + caminho);
                        File uploadedFile = new File(
                                "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho);
                        item.write(uploadedFile);

                    }

                    req.setAttribute("caminho", caminho);
                    req.getRequestDispatcher("AtualizarDadosUser").forward(req, resp);
                }

            }
        } catch (Exception e) {
            //            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }

}