Andrew Liu
Andrew Liu

Reputation: 329

Why aren't HttpServletResponse's PrintWriter contents being detected by the client until the end of the upload operation?

I have a servlet that uses the Apache Commons FileUpload package in an attempt to send progress information to the client. The problem is that, even though the servlet prints messages to the PrintWriter at the right times, the information is not received by the client until the end of the upload process.

Here's a snippet from the server:

servletFileUpload.setProgressListener(new ProgressListener() {

    private static final long BYTE_THRESHOLD = 10 * 1024 * 1024;
    private long bytesReadLastTime = -1;

    @Override
    public void update(final long bytesRead, final long contentLengthInBytes,
                       final int itemNumber) {
        if ((bytesRead / BYTE_THRESHOLD) == (bytesReadLastTime / BYTE_THRESHOLD)) {
            return;
        }
        String message = itemNumber + "|" + bytesRead + "|" + contentLengthInBytes;
        sendResponse(message); // Uses HttpServletResponse.getWriter().println()
        bytesReadLastTime = bytesRead;
    }

});

And here's a snippet from the client (JavaScript):

_responseHandler: function (response) {
    var data = response.split("|");
    var fileNumber = data[0];
    var bytesUploaded = data[1];
    var bytesTotal = data[2];
    console.log("File number: " + fileNumber +
        ", Bytes uploaded: " + bytesUploaded +
        ", Bytes total: " + bytesTotal);
    }
}

When I upload a large file, I see that the servlet's sendResponse() method gets called multiple times, as expected, at the correct intervals. But using Chrome's developer console, I see that _responseHandler doesn't get called until the end of the upload operation, and then it gets called a bunch of times (as if all the messages from the servlet got bunched up at the end).

In case it is relevant, my servlet runs locally for development purposes.

Upvotes: 0

Views: 33

Answers (1)

user207421
user207421

Reputation: 310957

HTTP is a request-reponse protocol. The client doesn't look for a response until it has finished sending a request.

Upvotes: 2

Related Questions