简体   繁体   中英

How to download a file from node server(using only node modules, no express, etc)

Im currently writing a handler for a download feature. When the user clicks on the download button from his\\her browser the download handler is called, which will then initiate the download(mp3 files only). I had this working on php, but I have since changed everything on my project to Node and I can't seem to get this last part working on Node.

This is the php code I had working before:

<?php 
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=".($_GET['title']));
  readfile($_GET['path']);
?>

This is the the new code for Node:

function download(response, request){

 var body = [];
   request.on('data', function(chunk) {
   body.push(chunk);
 });

 request.on('end', function() {
    
   body = Buffer.concat(body).toString();
   var data = qs.parse(body);
   var title = data.songTitle;
   var filePath =  __dirname + "/../myproject/songs/"+title+".mp3";
  
   fs.open(filePath,'r',function(err, fd){
      
      if(!err){
          
          fs.readFile(fd, function(err, data){
             
             if(!err){
                
                var rs = fs.createReadStream(filePath);
                response.writeHead(200, {"Content-Type": "application/octet-stream", 
                                         "Content-Disposition": "attachment; filename="+title+".mp3",
                                         "Content-Length" : data.length});
                rs.pipe(response);
                response.on("end",function(){
                    fs.close(fd);
                });  
                
             }else{
                 
                 console.log("Error while trying to read: ", err); 
                 
             }
             
          });
          
      }else{
          console.log("Error could not open: ", err);
      }
      
  });

  
});

When trying to download, I do not get any errors but nothing happens. I have also tried "audio/mpeg3" for content-type, and nothing. Any ideas on what's going on? I'm trying to do this without using third-party modules. Please note that the function download in not passed as the callback function of http.createServer(). So the order of response and request is not the issue :)

It looks like you switched request and response . Also, instead of using fs.open()/fs.readFile() to determine file size, you can use fs.stat() , which should be much more resource-friendly (since it doesn't require loading the entire file into memory first):

function download(request, response) {
  var body = [];

  request.on('data', function(chunk) {
    body.push(chunk);
  });

  request.on('end', function() {
    var data     = qs.parse(Buffer.concat(body).toString());
    var title    = data.songTitle;
    var filePath = title + '.mp3';

    fs.stat(filePath, function(err, stats) {
      if (err) {
        response.statusCode = 500;
        return response.end();
      }
      response.writeHead(200, {
        "Content-Type"        : "application/octet-stream",
        "Content-Disposition" : "attachment; filename="+title+".mp3",
        "Content-Length"      : stats.size,
      });
      fs.createReadStream(filePath).pipe(response);
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM