不确定我做错了什么......
我有一个节点js webserver,应该从ajax帖子将mp3文件保存到磁盘。该帖子包含一个mp3文件,该文件是由browser.js在浏览器中创建的wav文件构建的。
在我的requestHandler中,我有以下代码:
var
formidable = require('formidable'),
http = require('http'),
path = require('path'),
fs = require('fs');
function requestHandler(req, res) {
var requestPath = path.basename(req.url) || 'index.html',
ext = path.extname(requestPath),
localFolder = __dirname + '/public/',
uploadFolder = __dirname + '/uploads/';
if(requestPath === 'uploadmp3' && req.method === 'POST') {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if(err) {
console.error(err.message);
return;
}
var mp3File = uploadFolder + fields.fname;
var base64File = new Buffer(fields.data, 'binary').toString('base64');
var decodedFile = new Buffer(base64File, 'base64').toString('binary');
fs.writeFileSync(mp3File, decodedFile, 'base64', function(err){
if(err) {
return console.log(err);
}
console.log('written to disk: ' + mp3File);
});
res.writeHead(200, {'Content-Type:' : 'text/plain'});
res.write(mp3File+ ' \n\n');
res.end('\n');
});
return;
}
}
结果是我将文件保存到磁盘,但是虽然它的大小正确,但时间设置不正确,播放持续一秒钟。
我可以用php保存它没有问题... mp3文件播放完美,但我真的需要这个在节点js上工作。
答案 0 :(得分:3)
您需要使用Stream将内容保存到磁盘。根据您的实施:
var fs = require('fs');
if(requestPath === 'uploadmp3' && req.method === 'POST') {
var mp3File = uploadFolder+'audio_feedback_' + new Date().getTime() + '.mp3';
var mp3_file = fs.createWriteStream(mp3File);
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.writeHead(200, {'Content-Type:' : 'text/plain'});
res.write(mp3File+ ' is written to disk');
res.end('\n');
});
});
}
希望这有帮助。
答案 1 :(得分:-1)
我已将其修复为:
if(requestPath === 'uploadmp3' && req.method === 'POST') {
var mp3 = '';
var mp3File = uploadFolder+'audio_feedback_' + new Date().getTime() + '.mp3';
// req.setEcoding('base64');
req.on('data', function(data){
console.log("loading... \n");
mp3 += data;
});
req.on('end', function(){
console.log("request completed");
fs.open(mp3File, 'w', function(err, fd) {
if(err) {
return console.log(err);
}
// console.log(mp3File + ' file was read...');
fs.writeFile(mp3File, mp3, 'base64', function(err){
if(err) {
return console.log(err);
}
console.log('written to disk: ' + mp3File);
});
});
res.writeHead(200, {'Content-Type:' : 'text/plain'});
res.write(mp3File+ ' is written to disk');
res.end('\n');
});
}