开发者

How do you initiate/force a download for files that reside externally in PHP or other language?

开发者 https://www.devze.com 2022-12-22 19:56 出处:网络
If you have images or other files that reside externally, how do force the browser to download the link when a user click on it?

If you have images or other files that reside externally, how do force the browser to download the link when a user click on it?

The use of "Content-disposition: attachment;" header would do that, but it is not working for files that resides externally without r开发者_运维知识库eading and importing the file locally.


You will have to load the resource on the server first. You might want to do some caching also:

<?php
  header("Content-disposition: attachment; filename=myfile.jpg");
  echo file_get_contents("http://host.tld/path/to/myfile.jpg");
?>


This is not possible. You cannot dictate a client how to handle a different resource than the currently requested one.

You could only use a proxy to fetch the external external file and pass it to the client.


I don't think it is possible to force a file download if you are not controlling the HTTP headers. Content-disposition: attachment is the only way I know of to accomplish this.

Though this is probably not going to work, my only guess would be trying to combine Content-disposition with a Location header:

Content-disposition: attachment; filename=myfile.jpg
Location: http://www.somesite.com/myfile.jpg

(it's a long shot, probably invalid and/or just bad practice)


I use a combination of the aforementioned "Content-Disposition" header, as well as forcing the type:

header("Content-type: attachment/octet-stream");
header('Content-disposition: attachment; filename="'.$filename.'"');


I use a method similar to this for downloading mp4 files, could work for text files:

$file=fopen('http://example.com/example.txt','r');
header("Content-Type:text/plain");
header("Content-Disposition: attachment; filename="example.txt");
fpassthru($file);


You can use the download attribute. Just add download = 'filename.extension' to the download link:

 <a link='mysite.com/sfsf.extension' download='filenameuwant.extension'></a>
0

精彩评论

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