Search code examples
node.jsperlhttpresponseperl-module

How to download the file uploaded in the nodejs server


I am uploading a file in the node.js server. Below is the code for it.

  var formData = new FormData();
  formData.append('part1', fs.createReadStream(file1));
  formData.append('part2', fs.createReadStream(file2));

  formData.submit({
    host: 'xyz',
    port: 4354,
    path: '/handler',
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/mixed; boundary=' + formData.getBoundary()
    }
  }, function (error, response, body) {

    if (!error && response.statusCode === 200) {
     // Success case
    } else {
     // Failure case
    }

  });

Now, how to download that file in a perl server???

Tried HTTP::Response's decode_content() method. It is logging the response like below. Below I don't find any easier way to download the file.

 ----------------------------401882132761579819223727^M
Content-Disposition: form-data; name="fileContent"; filename="filepath"^M
Content-Type: application/octet-stream^M
^M   
FileContent FileContent FileContent FileContentFileContentFileContent
FileContentFileContentFileContentFileContentFileContentFileContentFileContent
FileContentFileContentFileContentFileContentFileContentFileContentFileContent  
----------------------------401882132761579819223727--^M

Solution

  • Solved this issue using MIME::Parser of Perl

     my $request = $r->as_string //$r is the HTTP::Request object
     $request =~ s/^[^\n]*\n//s;
    
     my $parser = MIME::Parser->new();
     $parser->output_to_core(1);
    
     my $ent = $parser->parse_data();  
    
     my $part1 = $ent->parts(0); // First file
     my $filename1 = $part1->head->recommended_filename
     my $content1 = $part1->bodyhandle->as_string
    
     my $part2 = $ent->parts(1); // Second file
     my $filename1 = $part2->head->recommended_filename
     my $content1 = $part2->bodyhandle->as_string
    

    $part1 and $part2 will be of types MIME::Entity objects and used suitable methods as per my requirements to read their content.