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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:com.exilant.exility.core.XLSHandler.java

/**
 * This method returns FileItem handler out of file field in HTTP request
 * /*from  www. j  a  v a  2  s. c o m*/
 * @param req
 * @return FileItem
 * @throws IOException
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
public static FileItem getFileItem(HttpServletRequest req) throws IOException, FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    /*
     * we can increase the in memory size to hold the file data but its
     * inefficient so ignoring to factory.setSizeThreshold(20*1024);
     */
    ServletFileUpload sFileUpload = new ServletFileUpload(factory);
    List<FileItem> items = sFileUpload.parseRequest(req);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            return item;
        }
    }

    throw new FileUploadException("File field not found");

}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);//w  w  w  . j a v a2  s.  co  m

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

private static MultipartEntity getMultipartEntity(HttpServletRequest request) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Enumeration<String> en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String name = en.nextElement();
        String value = request.getParameter(name);
        try {//  w  ww.j a  va2s.  co  m
            if (name.equals("file")) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(10000000);// 10 Mo
                List items = upload.parseRequest(request);
                Iterator itr = items.iterator();
                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(item.getName());
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(item.get());
                    fos.flush();
                    fos.close();
                    entity.addPart(name, new FileBody(file, "application/zip"));
                }
            } else {
                entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8")));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileUploadException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }

    return entity;

}

From source file:com.news.util.UploadFileUtil.java

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;/*w  ww.  ja v a 2 s. c o m*/
    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:com.fjn.helper.common.io.file.upload.FileUploadHelper.java

/**
 * ???//ww  w.  ja v a2 s.c om
 * @param request 
 * @param encoding encoding ?????character?{@link EncodingUtil}
 * @return ?
 * @see {@link #getFormFiledToFileItemMap(HttpServletRequest, String) }
 * @see {@link ServletFileUpload#parseRequest(HttpServletRequest)}
 */
public static List<FileItem> getFormFiledItmes(HttpServletRequest request, String encoding) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(defaultSizeThreshold);
    ServletFileUpload fileUploader = new ServletFileUpload(factory);
    fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
    List<FileItem> fileItems = null;
    try {
        // form?
        fileItems = fileUploader.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return fileItems;
}

From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String processFileUpload(HttpServletRequest request, HttpServletResponse response,
        RequestModel req) {/* w  ww.java 2s  .  c om*/
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads");
    FileOps.createDir(uploadDirName);
    File storageDir = new File(uploadDirName);
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName.length() > 0) {
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    uploadedFile = new File(storageDir, fileName);
                    try {
                        item.write(uploadedFile);
                        uploaded = true;
                    } catch (Exception ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        if (uploaded) {
            return SpServerLogic.getDocUploadResponse(req, uploadedFile);
        } else {
            if (paraMap.containsKey("xmlName")) {
                return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName"));
            }
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:msec.org.FileUploadServlet.java

static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer,
        HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    //System.out.printf("temporary directory:%s", tmpDir);

    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");

    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);/*from   ww  w  .ja  v  a2 s  .  co  m*/

    // Parse the request
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {//k -v

                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {

                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator
                        + fileName;
                //System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }

        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

}

From source file:dk.clarin.tools.userhandle.java

@SuppressWarnings("unchecked")
public static List<FileItem> getParmList(HttpServletRequest request) throws ServletException {
    List<FileItem> items = null;
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    if (is_multipart_formData) {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*/*from www . j  a  v a 2  s .com*/
        *Set the size threshold, above which content will be stored on disk.
        */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
        * Set the temporary directory to store the uploaded files of size above threshold.
        */
        File tmpDir = new File(ToolsProperties.tempdir);
        if (!tmpDir.isDirectory()) {
            throw new ServletException("Trying to set \"" + ToolsProperties.tempdir
                    + "\" as temporary directory, but this is not a valid directory.");
        }
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            items = (List<FileItem>) uploadHandler.parseRequest(request);
        } catch (FileUploadException ex) {
            logger.error("Error encountered while parsing the request: " + ex.getMessage());
        }
    }
    return items;
}

From source file:Model.Picture.java

public static ArrayList<String> upload(HttpServletRequest request, int type) {
    ArrayList<String> errors = new ArrayList<String>();
    ArrayList<String> pictureNames = new ArrayList<String>();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(Constants.UPLOAD_SIZE_THRESHOLD);
    new File(Constants.TEMP_DIR).mkdirs();
    factory.setRepository(new File(Constants.TEMP_DIR));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(Constants.MAX_UPLOAD_SIZE);

    try {/*from w  w w  . j  a v  a2  s  .  com*/
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fileItem = (FileItem) i.next();
            String fileName = fileItem.getName();

            if (type == EXCEL_UPLOAD)
                errors.addAll(upload_excel(fileName, fileItem));
            else if (type == PICTURE_UPLOAD)
                errors.addAll(upload_picture(fileName, fileItem, pictureNames));
        }
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        e.printStackTrace(System.out);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }

    if (type == PICTURE_UPLOAD)
        DataBaseTools.insertAndUpdateRecords(pictureNames);

    return errors;
}

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;// ww  w .  j a va2  s . c o  m
    }

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

        }

    }
}