有没有办法强制用户从href链接下载文件,而不是在浏览器窗口中打开它? [英] 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?

查看:115
本文介绍了有没有办法强制用户从href链接下载文件,而不是在浏览器窗口中打开它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我写了一个脚本,可以根据用户输入生成一个xml文件。生成文件后,下载链接如下所示:

 < a href =path / to / file.xml >下载档案< / a> 

但点击后会在浏览器中打开xml,我希望它在链接时开始下载点击代替。有没有什么办法可以达到这个目的?

是的,有。它确实需要指定一些标题。它的工作原理取决于你使用的是什么语言,但是这里有一个使用php的例子,摘自php.net:

 <?php 
//我们将输出PDF
头('Content-type:application / pdf');

//它将被称为downloaded.pdf
header('Content-Disposition:attachment; filename =downloaded.pdf'');

// PDF源文件位于original.pdf中
readfile('original.pdf');
?>

基本上,我们首先告诉客户端我们发送的是什么类型的文件,然后告诉客户端我们发送的是附件,它是名称,而不是要显示的页面,然后我们打印/读取文件到输出。



鉴于您已经使用php来生成xml文件,我建议将上面的头文件命令添加到生成xml文件的代码中,然后查看是否有这个技巧。


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:

<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.

这篇关于有没有办法强制用户从href链接下载文件,而不是在浏览器窗口中打开它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆