dimanche 10 septembre 2017

Uploading mp3 to NodeJS Express server corrupts file

I would like to upload an MP3 file from my web client to a Node Express server. I can upload the file, then write it to disk. However, the file gets corrupted and I cannot play the song using an MP3 player.

If it makes a difference, the file is being uploaded from an OS X machine, then gets written to an Ubuntu server. The size of the uploaded of the uploaded file is larger than the original. I receive no errors in this workflow. Nothing goes wrong until I start to play the file.

Please see below for my code. Any ideas about why I'm experiencing this?

CLIENT

uploadSong: (song) => {
  fetch('http://localhost:8080/song', {
    method: 'PUT',
    headers: {
      'Content-Type': 'audio/mpeg',
    },
    body: song
  })
  .then( response => {
    console.log("Got response after uploading song:", response);
  })
  .catch( error => {
    console.log("Error in Firebase AC upload song: ", error);
  });
}

SERVER

app.put("/song", (req, res) => {
  var mp3SongName = 'test.mp3';
  var mp3_file = fs.createWriteStream(mp3SongName);

  mp3_file.on('open', function (fd) {
    req.on('data', function(data){
        console.log("loading... \n");
        mp3_file.write(data);
    }); 

    req.on('end', function(){
        console.log("finalizing...");
        mp3_file.end();
        res.sendStatus(200);
    });
  });
}

Aucun commentaire:

Enregistrer un commentaire