简体   繁体   中英

Link to a PDF in html, the file has no extension, but I know it is pdf how to make it open appropriately

First post. I'm working on a project for a client where they have pdf files uploaded to a file structure (LAMP Stack) but the files have no extensions on them. Under the assumption that those files have to be PDF how would I get the browsers to understand that, and open them accordingly? Obviously with adding the file extensions this would suddenly work but I can't change the way their system works, it would result in too many changes and they are on a tight deadline. As for saving a temporary copy somewhere, I could do that, but I was hoping for a better solution. Is there a way to suggest to the browsers that they open a file a certain way?

Any thoughts guys/gals?

You just set the application type and file name in the headers, like so:

// This points to the file in question, note that it doesn't 
// care whether it has an extension on the name or not.
$filePathOnDisk = '/path/to/your/pdffile';

// You can make this whatever you like, it doesn't have to 
// be the same as the file name on the disk! This is the name of the file your end 
// user will see when they are asked if they want to save. open, etc in the browser.
$fileName = 'file.pdf'; 

$data = file_get_contents($filePathOnDisk); 
header("Content-type: application/pdf");
header("Content-disposition: attachment;filename=$fileName");
echo $data;

See PHP: stream remote pdf to client browser and Proper MIME media type for PDF files for reference as well.

Tested

You can use the following which will prompt the user to save the (PDF) file on their computer.

Notice the different file names.

One is the file that will be uploaded/prompted to the user download_example.pdf , while the other is the file without an extension as set in readfile('example');

<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="download_example.pdf"');
readfile('example');
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM