简体   繁体   English

上载mp3文件并在node.js中播放上载的文件

[英]Uploading mp3 files and playing the uploaded files in node.js

I am trying to upload some files, through an HTML form, in my local drive, which I was able to complete successfully. 我正在尝试通过HTML表单在本地驱动器中上载一些文件,并能够成功完成。 However, when attempting to play the mp3 uploaded file, by accessing the url of the "mp3 player", the server redirects me to the uploading page and I can not understand why this happens. 但是,当尝试播放mp3上传的文件时,通过访问“ mp3播放器”的url,服务器将我重定向到上传页面,我无法理解为什么会发生这种情况。 I am quite a begginer, when it comes to node.js and I do not really know that much about JavaScript, as I have little experience with it. 当涉及到node.js时,我是一个初学者,而我对JavaScript的了解并不多,因为我对此经验不足。 You can check the code below: 您可以检查以下代码:

var http = require('http'),
fs = require('fs'),
filePath = './test.mp3',
stat = fs.statSync(filePath);
var formidable = require('formidable');

http.createServer(function(request, response) {
  //fs.createReadStream(filePath).pipe(response);

  if(request.url == '/playUploadedFile') {
    fs.createReadStream(filePath).pipe(response);
    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size,
    });
  }

  if (request.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(request, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = __dirname + '/' + files.filetoupload.name;
      filePath = newpath;
      console.log(filePath);
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        response.write('File uploaded and moved!');
        //request.url = '/playUploadedFile';
        response.end();
      });
 });
  } else {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    response.write('<input type="file" name="filetoupload"><br>');
    response.write('<input type="submit">');
    response.write('</form>');
    return response.end();
  }

}).listen(8080)

In order to serve static file you have to declare your upload path to static. 为了提供静态文件,您必须声明您的静态上传路径。 This way node understands the files within the specified path needs to be served exactly the way it is. 通过这种方式,节点了解指定路径中的文件需要按其原样提供服务。 The easiest way to do this is to use express https://expressjs.com/en/starter/static-files.html . 最简单的方法是使用express https://expressjs.com/en/starter/static-files.html But you can also use node-static https://www.npmjs.com/package/node-static package as well. 但是,您也可以使用静态节点https://www.npmjs.com/package/node-static软件包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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