开发者

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?

Basically I wrote a script that generates a xml file 开发者_如何学Cbased on user input. After the file is generated a download link appears like so:

<a href="path/to/file.xml">Download File</a>

But when clicked it opens the xml in the browser, I want it to start downloading when the link it clicked instead. Is there any way to achieve that?


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.


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>


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜