Search in sources :

Example 86 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project ghostdriver by detro.

the class FileUploadTest method checkFileUploadCompletes.

@Test
public void checkFileUploadCompletes() throws IOException {
    WebDriver d = getDriver();
    // Create the test file for uploading
    File testFile = File.createTempFile("webdriver", "tmp");
    testFile.deleteOnExit();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile.getAbsolutePath()), "utf-8"));
    writer.write(FILE_HTML);
    writer.close();
    server.setHttpHandler("POST", new HttpRequestCallback() {

        @Override
        public void call(HttpServletRequest req, HttpServletResponse res) throws IOException {
            if (ServletFileUpload.isMultipartContent(req) && req.getPathInfo().endsWith("/upload")) {
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory(1024, new File(System.getProperty("java.io.tmpdir")));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                List<FileItem> items;
                try {
                    items = upload.parseRequest(req);
                } catch (FileUploadException fue) {
                    throw new IOException(fue);
                }
                res.setHeader("Content-Type", "text/html; charset=UTF-8");
                InputStream is = items.get(0).getInputStream();
                OutputStream os = res.getOutputStream();
                IOUtils.copy(is, os);
                os.write("<script>window.top.window.onUploadDone();</script>".getBytes());
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                return;
            }
            res.sendError(400);
        }
    });
    // Upload the temp file
    d.get(server.getBaseUrl() + "/common/upload.html");
    d.findElement(By.id("upload")).sendKeys(testFile.getAbsolutePath());
    d.findElement(By.id("go")).submit();
    // Uploading files across a network may take a while, even if they're really small.
    // Wait for the loading label to disappear.
    WebDriverWait wait = new WebDriverWait(d, 10);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("upload_label")));
    d.switchTo().frame("upload_target");
    wait = new WebDriverWait(d, 5);
    wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//body"), LOREM_IPSUM_TEXT));
    // Navigate after file upload to verify callbacks are properly released.
    d.get("http://www.google.com/");
}
Also used : WebDriver(org.openqa.selenium.WebDriver) HttpRequestCallback(ghostdriver.server.HttpRequestCallback) HttpServletResponse(javax.servlet.http.HttpServletResponse) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException) Test(org.junit.Test)

Example 87 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 88 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project jwt by emweb.

the class WebRequest method parse.

@SuppressWarnings({ "unchecked", "deprecation" })
private void parse(final ProgressListener progressUpdate) throws IOException {
    if (FileUploadBase.isMultipartContent(this)) {
        try {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            if (progressUpdate != null) {
                upload.setProgressListener(new org.apache.commons.fileupload.ProgressListener() {

                    public void update(long pBytesRead, long pContentLength, int pItems) {
                        progressUpdate.update(WebRequest.this, pBytesRead, pContentLength);
                    }
                });
            }
            // Parse the request
            List items = upload.parseRequest(this);
            parseParameters();
            Iterator itr = items.iterator();
            FileItem fi;
            File f = null;
            while (itr.hasNext()) {
                fi = (FileItem) itr.next();
                // else condition handles the submit button input
                if (!fi.isFormField()) {
                    try {
                        f = File.createTempFile("jwt", "jwt");
                        fi.write(f);
                        fi.delete();
                    } catch (IOException e) {
                        logger.error("IOException creating temp file {}", f.getAbsolutePath(), e);
                    } catch (Exception e) {
                        logger.error("Exception creating temp file {}", f.getAbsolutePath(), e);
                    }
                    List<UploadedFile> files = files_.get(fi.getFieldName());
                    if (files == null) {
                        files = new ArrayList<UploadedFile>();
                        files_.put(fi.getFieldName(), files);
                    }
                    files.add(new UploadedFile(f.getAbsolutePath(), fi.getName(), fi.getContentType()));
                } else {
                    String[] v = parameters_.get(fi.getFieldName());
                    if (v == null)
                        v = new String[1];
                    else {
                        String[] newv = new String[v.length + 1];
                        for (int i = 0; i < v.length; ++i) newv[i] = v[i];
                        v = newv;
                    }
                    v[v.length - 1] = fi.getString();
                    parameters_.put(fi.getFieldName(), v);
                }
            }
        } catch (FileUploadException e) {
            logger.info("FileUploadException", e);
        }
    } else
        parseParameters();
}
Also used : IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)88 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)65 FileItem (org.apache.commons.fileupload.FileItem)57 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)51 IOException (java.io.IOException)37 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)22 List (java.util.List)21 File (java.io.File)20 InputStream (java.io.InputStream)19 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)19 FileItemStream (org.apache.commons.fileupload.FileItemStream)19 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)16 ServletException (javax.servlet.ServletException)12 Map (java.util.Map)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 Iterator (java.util.Iterator)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6