【问题标题】:File is empty after downloading下载后文件为空
【发布时间】:2019-11-14 00:04:21
【问题描述】:

我正在尝试从服务器下载 csv 文件。文件正在下载,但它是空的。任何建议都非常受欢迎。文件名为 Maintenance_File.csv,位于 /home/netcool 位置。

#!/usr/bin/perl

use CGI ':standard';
use CGI::Carp qw(fatalsToBrowser);

my $files_location;
my $ID;
my @fileholder;

$files_location = "/home/netcool";

#$ID = param('file');
$ID = "Maintenance_File.csv";
#print "Content-type: text/html\n\n";
#print "ID =$ID";

if ($ID eq '') {
  print "You must specify a file to download.";
} else {
  $fileloc="/home/netcool/" . $ID;
  open(DLFILE, "$fileloc") || Error('open', 'file');
  @fileholder = <DLFILE>;
  close (DLFILE) || Error ('close', 'file');
  #print "Files data = @fileholder";
  print "Content-Type:application/octet-stream;\n";
  print "Content-Disposition:attachment;filename=\"$ID\"\r\n\n";
  print @fileholder
  #open(DLFILE, "< $fileloc") || Error('open', 'file');
  #while(read(DLFILE, $buffer, 100) ) {
  #  print("$buffer");
  #}
  #close (DLFILE) || Error ('close', 'file');

}

【问题讨论】:

  • 当我在新安装的 Ubuntu 上设置它并进行了一些微小的调整(因为我没有名为 /home/netcool/Maintenance_File.csv 的文件),它完全按预期工作。因此,问题在于您没有向我们展示的东西。你在什么系统上运行这个?是否有任何内容写入 Web 服务器错误日志?
  • 我的意思是,我可以建议对代码进行各种改进(为什么不使用use strictuse warnings?为什么加载CGI.pm 然后不使用它?你为什么要在 2019 年编写 CGI 程序?)但是,基本上,这种方法是有效的。

标签: perl download cgi


【解决方案1】:

您的代码有效。我不知道为什么它在您的环境中不起作用,但它在我的环境中按预期工作。也许您可以分享一些有关您运行它的环境的更多信息。

  • 您使用的是什么操作系统?
  • 您使用的是什么网络服务器?
  • 是否有任何内容写入 Web 服务器错误日志?

您的代码使用了一些相当过时的结构。重写为更现代的 Perl,它看起来像这样:

#!/usr/bin/perl

use strict;
use warnings;

use CGI 'header';
use CGI::Carp qw(fatalsToBrowser);

my $files_location = "/home/netcool";

my $filename = 'Maintenance_File.csv';

if (!$filename) {
  die "You must specify a file to download";
  exit;
}

print header(
  -type => 'application/octet-stream',
  -content_disposition => "attachment;filename=$filename",
);

my $fileloc = "$files_location/$filename";
open my $fh, '<', $fileloc or Error('open', 'file', $!);
print while <$fh>;
close $fh or Error ('close', 'file' );

sub Error {
  die "@_";
}

但我所做的任何修改都不会改变您代码的基本工作方式。我假设我的版本会以与您的原始版本相同的方式失败。

【讨论】:

  • 感谢@Dave Cross 的评论。该代码现在可以接受以下更改。打印标题(-type => 'text/csv', -content_disposition => "attachment;filename=$filename", );
  • 现在如果假设我在网页上给出了两个文本框并根据输入,需要形成文件名然后去下载。下面的代码不起作用
  • 我的 $files_location = "/home/netcool";我的 $first = $cgi->param('first_name');我的 $last = $cgi->param('last_name');打印“内容类型:文本/html\n\n”;打印 生成自引用 URL
    Circle:
    技术:
    EndOfHTML my $filename = $第一的 。 '_' 。 $last .'.csv';
  • @SaurabhJain:如果有人回答了您的问题,那么您应该接受他们的回答。如果您有后续问题,请在新帖子中提出。
猜你喜欢
  • 2019-03-06
  • 2023-01-26
  • 2011-03-09
  • 1970-01-01
  • 2014-09-19
  • 2020-02-12
  • 1970-01-01
  • 2014-12-01
相关资源
最近更新 更多