0

I am new to php and ajax. Im trying to force download a file from a list of documents. The functions below gets triggered using an ajax call after a button click.

function downloadDocument($filename) {

$file_path = ".........../DocUploader/Uploads/" . $filename;

if (file_exists($file_path)) {
    
    header("Content-Description: File Transfer");
    header("Content-Type: application/json");

    header("Content-Disposition: attachment; filename=\'" . $filename);

    readfile($file_path);


} else{
    echo "Document does not exist";
}};

Code for downloading file

Instead of downloading the file, I assume I am getting the file content as a response. I would really appreciate any advise on what I should do.

Response I get

Rashmika97
  • 37
  • 9

1 Answers1

0

First remove any echo's or output to the browser before sending any header, ie. remove the echo "File exists";

The file name should be encapsulated in quotations, ie. Content-Disposition: attachment; filename="filename.ext"

<?php
header("Content-Description: File Transfer");
header("Content-Type: application/json"); 
header('Content-Disposition: attachment; filename="'. $filename .'"');

readfile($file_path);

Keep in mind to set correct Content-type based on the real kind of the downloaded document, see topic What are all the possible values for HTTP "Content-Type" header?

You can dynamically detect the MIME type using PHP function mime_content_type()

And reference for PHP header.

ino
  • 2,345
  • 1
  • 15
  • 27