Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Sending file as "TEXT" or "BLOB"

by jcb (Parson)
on Feb 25, 2021 at 02:29 UTC ( [id://11128764] : note . print w/replies, xml ) Need Help??

in reply to Sending file as "TEXT" or "BLOB"

The correct solution here is to use the HTTP status code. This is why HTTP responses include a status code.

If the file exists, the server returns 200 OK and the file as application/zip. If the file does not exist, the server returns 404 Not Found. The client then distinguishes based on this.status: 200 for a BLOB is included and 404 for an error.

Here are the relevant bits of the revised JavaScript: (obviously untested)

xhttp.onreadystatechange = function() { if (this.readystate == 4) { if (this.status == 200) { if (xhttp.responseType == 'blob') { // existing goofy file download code here } else { // report internal error } } else if (this.status = 404) { // report error here } } }

As for the Perl code on the server side, you did not provide a SSCCE, so I can give only a broad outline of how the server processing should work:

  1. [whatever initial setup is needed]
  2. Read the form data from the client.
  3. Determine if the requirements to download a file have been met, and if so, which file is to be downloaded.
  4. Produce a reply, with either a 200 OK status if presenting a file, or 404 Not Found otherwise.

Replies are listed 'Best First'.
Re^2: Sending file as "TEXT" or "BLOB"
by haukex (Archbishop) on Feb 25, 2021 at 06:54 UTC
    The correct solution here is ...

    While that is an option, there is another way to look at it: this means that the client can't differentiate between an error the developer made, such as a typo in the URL or moving to another location, and an error the user made in requesting the file from, such as the target file not existing. That is an argument for adding an additional protocol layer, e.g. with JSON, as described in the other replies - 200 OK would mean the client reached the server successfully, and any other HTTP status code means that there is an issue in communicating with the server.

    Produce a reply, with either a 200 OK status if presenting a file, or 404 Not Found otherwise.

    TIMTOWTDI applies here as well. Since the script in the OP is simply serving up a raw file, this could theoretically be done more efficiently by the webserver itself, and the CGI script could be giving a 3xx redirect to that file. Granted, we currently don't have enough information about what the OP is doing to know if there might be access rights or similar to consider, but again, this is a suggestion to think about it in a more TIMTOWTDI way.