Is there a way to force the user to download a file from a href link rather than to open it in a browser window?

前端 未结 5 2056
灰色年华
灰色年华 2020-12-11 07:47

Basically I wrote a script that generates a xml file based on user input. After the file is generated a download link appears like so:



        
相关标签:
5条回答
  • 2020-12-11 08:00

    What happens when a browser sees a link is not dependent on the link, but rather on the target of the link. Your web server should send the appropriate header: Content-Disposition: attachment;filename="file.xml" to tell the browser that it should prompt to save the file instead of displaying it.

    0 讨论(0)
  • 2020-12-11 08:05

    download.php:

    header('Content-Type: text/xml');
    header('Content-Disposition: attachment; filename="file.xml"');
    readfile('/path/to/file.xml');
    

    HTML:

    <a href="download.php">Download</a>
    
    0 讨论(0)
  • 2020-12-11 08:11

    It depends on what the client computer does with XML files. If you doubleclick on a XML file, it will open in your browser probably.

    0 讨论(0)
  • 2020-12-11 08:20

    If you happen to be using Apache for your web server, and you always want to force downloading of XML files, there is a more efficient way to do what @chigley suggested. Just add the following to a .htaccess file.

    <Files *.xml>
    ForceType application/xml
    Header set Content-Disposition attachment
    </Files>
    
    0 讨论(0)
  • 2020-12-11 08:24

    Yeah, there is. It does require specifying some headers. Exactly how it works depends on what language you're using, but here's an example using php, taken off of php.net:

    <?php
    // We'll be outputting a PDF
    header('Content-type: application/pdf');
    
    // It will be called downloaded.pdf
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    
    // The PDF source is in original.pdf
    readfile('original.pdf');
    ?>
    

    Basically, first we tell the client what type of file we're sending, then we tell the client that what we're sending is an attachment, and it's name, instead of it being a page to display, and then finally we print/read the file to the output.

    Given that you're already using php to generate the xml file, I would suggest adding the header commands above to the code that generates the xml file, and see if that does the trick.

    0 讨论(0)
提交回复
热议问题