slugger415
slugger415

Reputation: 371

Uploaded files on Apache24 Windows server are corrupted

I have a Perl CGI script to upload files on my local Windows 10 machine running Apache24. The uploads seem to work fine but the MP3 and JPG files I'm testing with are corrupted.

I've also noticed text files are uploaded with extra line breaks in them, which I gather is a clue of some kind. The text files are otherwise readable.

I've based my script on Noah Petherbridge's progress bar script. That seems to work fine if I run it on an external server, but not on my local Windows server.

I don't know if I should post the entire script here, but here's the meaningful part.

use CGI;
use CGI::Carp "fatalsToBrowser";
my $q = new CGI (\&hook);

 sub hook {
        my ($filename,$buffer,$bytes_read,$file) = @_;

    $filename = $q->param("incoming");
    $handle   = $q->upload("incoming");
   open (FILE, ">/Apache24/htdocs/uploads/$filename") or die "Can't create file: $!";
    
    while (read($handle,$buffer,2048)) {
            print FILE $buffer;
    }
    close (FILE);
}

I don't know if this has something to do with my local Apache installation, or the perl script is inserting something. Any thoughts would be appreciated! thank you.

Upvotes: 1

Views: 67

Answers (1)

ikegami
ikegami

Reputation: 385789

By default, file reads and writes translate between LF and CR LF line endings on Windows. That makes no sense for files that aren't text files, so this is corrupting your files.

Replace

open (FILE, ">/Apache24/htdocs/uploads/$filename")
   or die "Can't create file: $!";

with

my $qfn = "/Apache24/htdocs/uploads/$filename";
open( my $fh, ">:raw", $qfn )
   or die( "Can't create file `$qfn`: $!\n" );

(The :raw is the relevant part. The rest of the changes are just improvements.)

Upvotes: 1

Related Questions