Downloading a file with a different name to the stored name

前端 未结 5 818
灰色年华
灰色年华 2020-11-30 08:37

Is it possible to let your user download a file with a different name?

For example, there is a file called \"4324ffsd34.jpg\". I want people to download it via down

相关标签:
5条回答
  • 2020-11-30 08:51

    Sure you can, just try something like this:

    $original_filename = '4324ffsd34.jpg';
    $new_filename = 'my_new_filename_is_detailled.jpg';
    
    // headers to send your file
    header("Content-Type: application/jpeg");
    header("Content-Length: " . filesize($original_filename));
    header('Content-Disposition: attachment; filename="' . $new_filename . '"');
    
    // upload the file to the user and quit
    readfile($original_filename);
    exit;
    

    Hope it helps!

    0 讨论(0)
  • 2020-11-30 08:56

    Nothing wrong with the above but I had to add:

    ob_clean();
    flush();
    

    before readfile

    otherwise I can not open the download jpg/png file

    0 讨论(0)
  • 2020-11-30 08:58

    There is also another way if you are using html5

    <a href="link/to/my/file/with/a/name/i/dont/like.jpg" download="MyFile.jpg">Download</a>
    

    Cheers :3

    0 讨论(0)
  • 2020-11-30 09:03

    Sure, use a Content-disposition header

    header('Content-Disposition: attachment; filename="filetodownload.jpg"');
    

    if you wish to provide a default filename, but not automatic download, this seems to work.

    header('Content-Disposition: filename="filetodownload.jpg"');
    
    0 讨论(0)
  • 2020-11-30 09:17
    <a href="4324ffsd34.jpg" download="filetodownload">Download</a>
    
    0 讨论(0)
提交回复
热议问题