0

I wrote a small script using only PHP to test file download functionality using a experimental API, where this worked fine. When I decided to commit this code to my project, I added the same code to the handler for my AJAX call, however it does not start the download as it did before.

I believe this is due to the fact I am using AJAX, however as I was using header() to initiate the file download on the client, I am at a loss as to how to work around this.

Can anyone suggest an alternative method to do this now?

AJAX:

    $.ajax({
        type: "POST",
        url: "handler.php",
        data: { 'action': 'downloadFile', 'filename': curSelectedFile },
        dataType: 'json',
        success: function(data)
        {
            //Success
        }
    });

PHP Handler:

case "downloadFile":
{
    $filename = '';

    if (isset($_POST["filename"]))
    {
        $filename = $_POST["filename"];
    }

    $pos = 0; // Position in file to start reading from
    $len = 32; // Length of bytes to read each iteration
    $count = 0; // Counter for the number of bytes in the file

    do
    {
        $result = $fm->getFileChunk($filename, $pos, $len);
        $chunk = $result->result;

        if (!empty($chunk))
        {
            $chunk = base64_decode($chunk);
            $count += strlen($chunk);

            echo $chunk;
        }

        $pos += $len;
    }
    while (!empty($chunk));

    header('Content-Disposition: attachment; filename="'. $filename .'"');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . $count);

    $response['status'] = "success";

    echo json_encode($response);

    break;
}

1 Answers1

1

You can encode your file in base64 and create File Object using JavaScript.

I wouldn't recommend this for large files!

Alternative:

Save your file on server and you can just retrieve file location and redirect using location.href in Ajax callback.

You can decode base64 using atob() and create typed array. refer to following link for creating Binary Object on client side. You create typed array like answered here.

Community
  • 1
  • 1
  • Thanks for the recommendation! I am indeed going to set a file size to limit this to very small files. Can you perhaps provide an example of using the File Object with the base64 encoding? I've never used this and not even finding anything on Google atm –  Mar 07 '15 at 06:41