Perl CGI to download a file via web browser

感情迁移 提交于 2019-12-03 16:01:28

Rearranging the HTML headers worked. here is the working script. one can use this as it is

use CGI;
my $html= new CGI;
#get the file name from URL ex. http://<server_IP>/cgi-bin/download.cgi?a=testing.txt
my $file= $html->param('a'); 
# $file is nothing but testing.txt
my $filepath= "/var/www/upload/$file";

print ("Content-Type:application/x-download\n");
print "Content-Disposition: attachment; filename=$file\n\n";

open FILE, "< $filepath" or die "can't open : $!";
binmode FILE;
local $/ = \10240;
while (<FILE>){
    print $_;
}

    close FILE;
 # use Unlink if u want to delete the files after download.
#unlink ($filepath);

I think you've just spelled your content-disposition header wrong. It should be "attachment", not "attachement".

Update (following comment below):

Ok, so looking further I see that you're printing a CGI header (Content-Type: text/html) followed by two newlines and then, later, printing more CGI headers and expecting the browser to notice them. The first blank line in your response will tell the browser that the headers are finished. So your second batch of headers will just be seen as content.

I also see that you are printing the contents of the file before your second set of headers. Which would make them footers rather than headers :-)

You need to re-order your code so that you only return one set of headers. And then you return the data.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!