Outputting files in PERL

I wish to export a comma delimited flat file database to the user's browser. Which should present them with a "Save As" box but I can't make it work below is what I have.

$newpath = "$basepath" . "AffDBExport.txt";

$|++; ##  Disable output buffering

$nl=$/; ##  Save the newline character
undef $/;
open(F,$newpath) || die $!;
binmode(F); ##  Open the file in binary mode.
$file_contents=<F>; ##  Read the entire file into a single variable
close(F);

$/=$nl; ##  Restore the newline character.

##  Print some junk MIME header
print "Content-type: application/csv\n\n";

print $file_contents;


noelhAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
dkjariwalaConnect With a Mentor Commented:
#!/usr/bin/perl

$filename = 'AffDBExport.txt';## use single quotes around string in which you don't need to do variable substitution.

$newpath = $basepath . $filename; ##You don't need to put quotes around the variable $basepath.

$|++; ##  Disable output buffering

$nl=$/; ##  Save the newline character
undef $/;
open(F,$newpath) || die $!;


##binmode(F); ##  No need to use binmode.
#no need to use binmode unless you are on Windows and dealing with binary files.
#As in your case, file is ascii, so dont use that code.


$file_contents=<F>; ##  Read the entire file into a single variable
close(F);

print "Content-Type: application/octetstream\n";
print "Content-Disposition: attachment; filename=$filename \n";
print "Pragma: no-cache\n"; ##added this so  that browser doesn't cache it.
print "Expires: 0\n\n";
print $file_contents;


Just check up my comments,
JD
0
 
maneshrCommented:
noelh,

REPLACE...

print "Content-type: application/csv\n\n";

WITH....

print "Content-type: application/octet-stream\n";
print "Content-disposition: filename='AffDBExport.txt'\n\n"

Let me know how that goes for you.
0
 
noelhAuthor Commented:
Nope, the browser still just showed the text, instead of offering a "Save As" Choice.

0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
dkjariwalaCommented:
Which browser you are using ??
JD
0
 
maneshrCommented:
noelh,

".. instead of offering a "Save As" Choice...."

Can you post the URL where one can see this script in action?

Meanwhile, i would suggest you REPLACE...

print "Content-type: application/octet-stream\n";

WITH...

print "Content-type: application/noelh\n";

& let me know how it goes.
0
 
dkjariwalaCommented:
Yeah, Agree with maneshr,

Put up the URL so that we can check in our browser.

JD


0
 
noelhAuthor Commented:
Sorry, upon double checking I noticed that I had not transfered your code correctly. Once I fixed my mistake it worked great. Thanks!!
0
 
dkjariwalaCommented:
Great !!

JD
0
All Courses

From novice to tech pro — start learning today.