user1826831
user1826831

Reputation: 765

How to detect a file-upload examining the http-message?

I want to detect if a Http-Request is a file-upload or not. I know, there are a view things that may indicate a file-upload:

There are a view Questions left:

How can I distinguish a file-upload from a normal html-form post? Does the browser use chunked-encoding for file-uploads? (As far as I know, that would be senseless, but I dont know a lot)

Upvotes: 1

Views: 2883

Answers (2)

zhizhideng
zhizhideng

Reputation: 156

Usually it can be detected by checking whether the request is multipart .

The following example code is c&p from Apache Commons FileUpload library

/**
 * Utility method that determines whether the request contains multipart
 * content.
 *
 * @param request The servlet request to be evaluated. Must be non-null.
 *
 * @return <code>true</code> if the request is multipart;
 *         <code>false</code> otherwise.
 */
public static final boolean isMultipartContent(
        HttpServletRequest request) {
    if (!"post".equals(request.getMethod().toLowerCase())) {
        return false;
    }
    String contentType = request.getContentType();
    if (contentType == null) {
        return false;
    }
    if (contentType.toLowerCase().startsWith(MULTIPART)) {
        return true;
    }
    return false;
}

where MULTIPART is

/**
 * Part of HTTP content type header.
 */
public static final String MULTIPART = "multipart/";

Upvotes: 2

jomofrodo
jomofrodo

Reputation: 1149

Checking for a multipart form submission just gets you through the front door. The problem is, you can have a multipart form submission that does not actually contain a file upload. If you want to know if you actually have an uploaded file, you need to search through the form parts. Like this:

public static int getUploadCount(HttpServletRequest request) throws Exception {
    int fileCt = 0;
    String[] tokens;
    String contentDisp;
    String fileName;
    // Search through the parts for uploaded files
    try{
        for (Part part : request.getParts()) {
            fileName = "";
            contentDisp = part.getHeader("content-disposition");
            // System.out.println("content-disposition header= "+contentDisp);
            tokens = contentDisp.split(";");
            for (String token : tokens) {
                if (token.trim().startsWith("filename")) {
                    fileName = token.substring(
                        token.indexOf("=") + 2, 
                        token.length() - 1
                    );
                }
            }

            if (!fileName.equals("")) {
                fileCt++;
            }
        }
    } catch (ServletException ex) {
        throw new Exception(ex);
    }
    return fileCt;
}

Upvotes: 1

Related Questions