gpt4 book ai didi

javascript - Node 文件传输在图像目录中上传 x 字节的图像,但已损坏

转载 作者:行者123 更新时间:2023-12-03 08:17:15 26 4
gpt4 key购买 nike

我正在使用 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');
});
});

关于javascript - Node 文件传输在图像目录中上传 x 字节的图像,但已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33885603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com