保存mp3为ajax post数据与节点js
save mp3 as ajax post data with node js
不知道我做错了什么…
我有一个节点js web服务器,应该保存mp3文件到磁盘从ajax后。这篇文章包含一个mp3文件,该文件是由browser中recorder.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.
您需要使用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');
});
});
}
我已经修复了:
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');
});
}
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 节点.js将变量显示为 HTML
- 如何解决'窗口未定义'终端上的节点JS出错
- S3文件上传文件对象使用节点js
- 在节点 js 中使用护照本地模块验证(登录)密码时出错
- 嵌套的promise节点js
- 使用节点JS发送电子邮件
- 节点JS重定向循环
- 起始节点.js用于并行的线程池
- 获取图像节点js的主色
- 调整节点js中的图像大小
- 节点JS express和控制台输出到命令行与浏览器
- 节点JS:时间机器坏了——timekeeper.travel不做时间旅行
- 如何访问日期并将其插入数据库?节点.JS&MongoDB
- 节点.js快速删除 req.body 不起作用
- 节点.js中的嵌套异步操作
- 如何在核心php应用程序中使用节点js json Web令牌库
- 使用节点js的Bootstrap和Jquery
- 节点.js加密输入/输出类型
- 节点.js在不可能的地方打印“未定义”