Respond to multipart file upload request before reading and saving file

Viewed 340

Is it possible to respond to a multipart/form-data request after reading the headers but before reading the file data from the request body and saving it to a temporary file?

I have a file upload servlet that accepts large files, and I would prefer if I could handle any pre-process checks from the request header before loading the entire file. For example, I need to check if the user is authenticated from session before processing and storing the file. It seems like I must call request.getPart() or any method that parses the request body before I send a response because otherwise the browser does not process the response. The problem is that with multipart/form-data requests, request.getPart() parses the body and also reads the file data and stores it to a temporary file on disk.

How can I read only the headers and send a response before loading the file from the request body

Here is an example:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // check session (header cookie)
    if (!isAuthenticated(request)) {
        // This does not work before reading body
        forwardLogin(request, response);
        return;
    }

    // Actually parse request body and save the data to a temporary file on disk
    Part filePart = request.getPart("file");

    // process file
}
0 Answers
Related