节点文件传输在images目录中上载x字节的图像,但已损坏
Node File transfer uploads x bytes of image in images directory but is corrupt
我正在使用Node的Busboy
模块来解析文件。首先上传一个文件->将上传的文件推送到images目录。我不知道为什么,但代码正在传输字节,即它确实创建了一个具有适当字节的图像,但当点击文件时,它已损坏。这是我的代码:
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
var fstream = fs.createWriteStream('./images/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
console.log("Upload Finished of " + filename);
});
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
data
事件可以多次发射。这里的解决方案很简单:只需将file
管道传输到一个可写流一次。例如:
var crypto = require('crypto');
var path = require('path');
// ...
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
// You will want to somehow sanitize `filename` if you are going to use
// it when use it as part of the filename on disk, as it could be maliciously
// constructed to overwrite to other parts of your filesystem.
//
// The solution I use here is to simply hash the filename, but you could
// use `path.resolve('./images/', filename)` instead and check that the
// result starts with `__dirname + '/images/'`.
var ext = path.extname(filename);
filename = crypto.createHash('sha1')
.update(filename, 'utf8')
.digest('hex') + ext;
var diskStream = fs.createWriteStream('./images/' + filename);
file.pipe(diskStream).on('finish', function() {
console.log('Finished writing file');
});
});
相关文章:
- 正在从字节数组加载图像内容
- 将字节转换为用于在HTML5画布上绘制的图像
- 在 MVC3 中将字节数组显示为图像
- 如何将Golang中的[][]字节发送到浏览器以解码为图像
- 在JavaScript IE8中将图像转换为字节代码
- 如何在 JSP/JavaScript 中将图像转换为字节数组
- JavaScript:从字节数组创建图像资源
- 仅使用 jQuery .load() 接收图像的字节码
- 如何将图像数据传递给 Controiller 并转换为字节
- 可以在三.js的字节数组中加载图像和模型
- JavaScript:从图像中删除字节(base64 字符串)
- 字节图像未从客户端浏览器保存在数据库中
- 如何使用javascript将图像转换为字节数组,仅将图像存储在sql server上
- 节点文件传输在images目录中上载x字节的图像,但已损坏
- 是否可以通过JavaScript (JSX脚本)在Photoshop中检查图像的大小(字节而不是像素)
- 将字节数组转换成图像
- 如何下载图像(显示保存对话框在浏览器中),这是在html2canvas从控制器在MVC创建的字节的形式
- Node js从web获取图像并将其转换为字节值数组
- 在json中传递base64字节的图像数组给webApi
- 如何获得实际的图像文件来检查Multer中的魔术字节