Daniel Price
Daniel Price

Reputation: 1142

AJAX JavaScript form catch file download and get file info

I've created a script that catches a Captcha forms submission. The form will normally download a file (mixture of formats, I.E exe, zip, etc), the usual way (in chrome, shows download at the bottom, downloads into "downloads" directory.

I don't want the script to actually store the downloaded on the users computer, so I've edited the form submission to handle the download with AJAX, and store the files data in a variable. Another function then uploads this script to a PHP page.

Is there any way to retrieve the information of the file that's downloading, file name, file type, etc? It could, for example be called 'Application.1.2.zip', but I don't know how to retrieve this data from the AJAX request that downloads the file. The only reason I need this, is to get the file type, so I can store the file under the correct format on the second domain.

The current process attempts to download a file from domain A (any file format) with AJAX, store the file in a variable, then upload the file to domain B also using AJAX.

Thanks, Dan.

Upvotes: 0

Views: 412

Answers (1)

meskobalazs
meskobalazs

Reputation: 16041

The Content-Disposition HTTP header could be solution for you. From the W3C RFC2616:

The Content-Disposition response-header field has been proposed as a means for the origin server to suggest a default filename if the user requests that the content is saved to a file. This usage is derived from the definition of Content-Disposition in RFC 1806 [35].

content-disposition = "Content-Disposition" ":"
                          disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )

An example is

    Content-Disposition: attachment; filename="fname.ext"

This way, you can do it in one request.

In JavaScript you can extract the filename similar to this:

var disposition = httpRequest.getResponseHeader('Content-Disposition');
var filename = disposition.substring(disposition.indexOf('=') + 1);

Upvotes: 1

Related Questions