Jack Maessen
Jack Maessen

Reputation: 1864

how to rename downloaded file via ajax

For downloading a file via ajax, i have this php code and it works fine

if($_POST['downloadfile']) {
    $downloadfile = $_POST['downloadfile'];
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename= $downloadfile");
    header("Content-Transfer-Encoding: binary");  

    @readfile($downloadfile);
    exit;
}

The value of $_POST['downloadfile'] is the path to the file ; like uploads/image.jpg

When downloading the file, the name of the file is created by the browser as uploads_image.jpg How can i force the browser to give it only the name image.jpg ?

I tried this with below with basename but ofcourse, this is not working :

header("Content-Disposition: attachment; filename= basename($downloadfile"));

Upvotes: 0

Views: 298

Answers (1)

Dave
Dave

Reputation: 5191

Modify that header line slightly so that a) the basename function is "seen" and executed b) the file name is enclosed in quotes in case it has a space in the name.

header('Content-disposition: attachment; filename="' . basename($downloadfile) . '"');

Upvotes: 1

Related Questions