Search in sources :

Example 41 with FileUploadException

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

the class CommonsFileUploadPartFactory method read.

public static Collection<Part> read(final HttpRequestImpl request) {
    // mainly for testing
    // Create a new file upload handler
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(REPO);
    final ServletFileUpload upload = new ServletFileUpload();
    upload.setFileItemFactory(factory);
    final List<Part> parts = new ArrayList<>();
    try {
        final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        final String enc = request.getCharacterEncoding();
        for (final FileItem item : items) {
            final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
            parts.add(part);
            if (part.getSubmittedFileName() == null) {
                String name = part.getName();
                String value = null;
                try {
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        if (enc == null) {
                            encoding = "UTF-8";
                        } else {
                            encoding = enc;
                        }
                    }
                    value = part.getString(encoding);
                } catch (final UnsupportedEncodingException uee) {
                    try {
                        value = part.getString("UTF-8");
                    } catch (final UnsupportedEncodingException e) {
                    // not possible
                    }
                }
                request.addInternalParameter(name, value);
            }
        }
        return parts;
    } catch (final FileUploadException e) {
        throw new IllegalStateException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Part(javax.servlet.http.Part) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 42 with FileUploadException

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

the class FileUploadTool method FileUpload.

public static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // 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();
                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 43 with FileUploadException

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

the class FileUploadServlet method FileUpload.

// 处理multi-part格式的http请求
// 将key-value字段放到fields里返回
// 将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
protected 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 = 200000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");
    upload.setSizeMax(MaxRequestSize);
    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;
                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.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}
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) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 44 with FileUploadException

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

the class FileUploadServlet method FileUpload.

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

Example 45 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project zm-mailbox by Zimbra.

the class FileUploadServlet method handleMultipartUpload.

@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete) throws IOException, ServiceException {
    List<FileItem> items = null;
    String reqId = null;
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    try {
        items = upload.parseRequest(req);
        if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
            drainRequestStream(req);
            mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled", acct.getName());
            sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
            return Collections.emptyList();
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // at least one file was over max allowed size
        mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadBase.InvalidContentTypeException e) {
        // at least one file was of a type not allowed
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadException e) {
        // parse of request failed for some other reason
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
        return Collections.emptyList();
    }
    String charset = "utf-8";
    LinkedList<String> names = new LinkedList<String>();
    HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
    if (items != null) {
        for (Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
            FileItem fi = it.next();
            if (fi == null)
                continue;
            if (fi.isFormField()) {
                if (fi.getFieldName().equals("requestId")) {
                    // correlate this file upload session's request and response
                    reqId = fi.getString();
                } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
                    // get the form value charset, if specified
                    charset = fi.getString();
                } else if (fi.getFieldName().startsWith("filename")) {
                    // allow a client to explicitly provide filenames for the uploads
                    names.clear();
                    String value = fi.getString(charset);
                    if (!Strings.isNullOrEmpty(value)) {
                        for (String name : value.split("\n")) {
                            names.add(name.trim());
                        }
                    }
                }
                // strip form fields out of the list of uploads
                it.remove();
            } else {
                if (fi.getName() == null || fi.getName().trim().equals("")) {
                    it.remove();
                } else {
                    filenames.put(fi, names.isEmpty() ? null : names.remove());
                }
            }
        }
    }
    // restrict requestId value for safety due to later use in javascript
    if (reqId != null && reqId.length() != 0) {
        if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
            mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
            sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
            return Collections.emptyList();
        }
    }
    // empty upload is not a "success"
    if (items == null || items.isEmpty()) {
        mLog.info("No data in upload for reqId: %s", reqId);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
        return Collections.emptyList();
    }
    // cache the uploaded files in the hash and construct the list of upload IDs
    List<Upload> uploads = new ArrayList<Upload>(items.size());
    for (FileItem fi : items) {
        String name = filenames.get(fi);
        if (name == null || name.trim().equals(""))
            name = fi.getName();
        Upload up = new Upload(acct.getId(), fi, name);
        mLog.info("Received multipart: %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        uploads.add(up);
    }
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
    return uploads;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) LinkedList(java.util.LinkedList) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.commons.fileupload.FileUploadBase) 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)23 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