Search in sources :

Example 21 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project zuul by Netflix.

the class FilterScriptManagerServlet method handlePostBody.

private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    org.apache.commons.fileupload.FileItemIterator it = null;
    try {
        it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream stream = it.next();
            InputStream input = stream.openStream();
            // NOTE: we are going to pull the entire stream into memory
            // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
            byte[] uploadedBytes = getBytesFromInputStream(input);
            input.close();
            if (uploadedBytes.length == 0) {
                setUsageError(400, "ERROR: Body contained no data.", response);
                return null;
            }
            return new String(uploadedBytes);
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
    return null;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 22 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project OpenAttestation by OpenAttestation.

the class WLMDataController method uploadManifest.

public ModelAndView uploadManifest(HttpServletRequest req, HttpServletResponse res) {
    log.info("WLMDataController.uploadManifest >>");
    req.getSession().removeAttribute("manifestValue");
    ModelAndView responseView = new ModelAndView(new JSONView());
    List<Map<String, String>> manifestValue = new ArrayList<Map<String, String>>();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    System.out.println(isMultipart);
    if (!isMultipart) {
        responseView.addObject("result", false);
        return responseView;
    }
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                String[] lines = item.getString().split("\\r?\\n");
                for (String values : lines) {
                    if (values.length() > 2) {
                        String[] val = values.split(":");
                        if (val.length == 2) {
                            Map<String, String> manifest = new HashMap<String, String>();
                            manifest.put(val[0], val[1]);
                            manifestValue.add(manifest);
                        } else {
                            responseView.addObject("result", false);
                            return responseView;
                        }
                    }
                }
            }
        }
        log.info("Uploaded Content :: " + manifestValue.toString());
        req.getSession().setAttribute("manifestValue", manifestValue);
        /*responseView.addObject("manifestValue",manifestValue);*/
        responseView.addObject("result", manifestValue.size() > 0 ? true : false);
    } catch (FileUploadException e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    } catch (Exception e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    }
    log.info("WLMDataController.uploadManifest <<<");
    return responseView;
}
Also used : HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException) WLMPortalException(com.intel.mountwilson.common.WLMPortalException) FileItem(org.apache.commons.fileupload.FileItem) JSONView(com.intel.mountwilson.util.JSONView) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) Map(java.util.Map) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 23 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project sonarqube by SonarSource.

the class CommonsMultipartRequestHandler method handleRequest.

/**
     * <p> Parses the input stream and partitions the parsed items into a set
     * of form fields and a set of file items. In the process, the parsed
     * items are translated from Commons FileUpload <code>FileItem</code>
     * instances to Struts <code>FormFile</code> instances. </p>
     *
     * @param request The multipart request to be processed.
     * @throws ServletException if an unrecoverable error occurs.
     */
public void handleRequest(HttpServletRequest request) throws ServletException {
    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
    // Create and configure a DIskFileUpload instance.
    DiskFileUpload upload = new DiskFileUpload();
    // The following line is to support an "EncodingFilter"
    // see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    // Set the maximum size that will be stored in memory.
    upload.setSizeThreshold((int) getSizeThreshold(ac));
    // Set the the location for saving data on disk.
    upload.setRepositoryPath(getRepositoryPath(ac));
    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();
    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }
    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) DiskFileUpload(org.apache.commons.fileupload.DiskFileUpload) Hashtable(java.util.Hashtable) Iterator(java.util.Iterator) ModuleConfig(org.apache.struts.config.ModuleConfig) ArrayList(java.util.ArrayList) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 24 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project MSEC by Tencent.

the class FileUploadTool method FileUpload.

//处理multi-part格式的http请求
//将key-value字段放到fields里返回
//将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
public static 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);
    // Parse the request
    try {
        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();
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 25 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project OpenClinica by OpenClinica.

the class FileUploadHelper method getFiles.

@SuppressWarnings("unchecked")
private List<File> getFiles(HttpServletRequest request, ServletContext context, String dirToSaveUploadedFileIn) {
    List<File> files = new ArrayList<File>();
    // FileCleaningTracker fileCleaningTracker =
    // FileCleanerCleanup.getFileCleaningTracker(context);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(getFileProperties().getFileSizeMax());
    try {
        // Parse the request
        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()) {
                request.setAttribute(item.getFieldName(), item.getString());
            // DO NOTHING , THIS SHOULD NOT BE Handled here
            } else {
                getFileProperties().isValidExtension(item.getName());
                files.add(processUploadedFile(item, dirToSaveUploadedFileIn));
            }
        }
        return files;
    } catch (FileSizeLimitExceededException slee) {
        throw new OpenClinicaSystemException("exceeds_permitted_file_size", new Object[] { String.valueOf(getFileProperties().getFileSizeMaxInMb()) }, slee.getMessage());
    } catch (FileUploadException fue) {
        throw new OpenClinicaSystemException("file_upload_error_occured", new Object[] { fue.getMessage() }, fue.getMessage());
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ArrayList(java.util.ArrayList) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) File(java.io.File) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)27 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)20 FileItem (org.apache.commons.fileupload.FileItem)16 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)14 IOException (java.io.IOException)12 ArrayList (java.util.ArrayList)8 File (java.io.File)5 InputStream (java.io.InputStream)5 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)5 FileItemStream (org.apache.commons.fileupload.FileItemStream)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 List (java.util.List)4 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)4 ServletException (javax.servlet.ServletException)3 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)3 HttpRequestCallback (ghostdriver.server.HttpRequestCallback)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2