cos*_*sta 8 javascript node.js express
我从前端客户端发送一个文件,在服务器端我有这样的东西:
{ name: 'CV-FILIPECOSTA.pdf',
data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 62 6a 0d 3c 3c 2f 4d 65 74 61 64 61 74 61 20 32 20 30 20 52 2f 4f 43 50 72 6f 70 65 72 ... >,
encoding: '7bit',
mimetype: 'application/pdf',
mv: [Function: mv] }
Run Code Online (Sandbox Code Playgroud)
我需要的是创建文件可能基于那里的缓冲区,我该怎么做?
我已经搜索了很多,但没有找到任何解决方案。
这是我到目前为止尝试过的:
router.post('/upload', function(req, res, next) {
if(!req.files) {
return res.status(400).send("No Files were uploaded");
}
var curriculum = req.files.curriculum;
console.log(curriculum);
curriculum.mv('../files/' + curriculum.name, function(err) {
if (err){
return res.status(500).send(err);
}
res.send('File uploaded!');
});
});
Run Code Online (Sandbox Code Playgroud)
您可以使用Buffer可用NodeJS:
let buf = Buffer.from('this is a test');
// buf equals <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
let str = Buffer.from(buf).toString();
// Gives back "this is a test"
Run Code Online (Sandbox Code Playgroud)
也可以在重载from方法中指定编码。
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
// This tells that the first argument is encoded as a hexadecimal string
let str = buf2.toString();
// Gives back the readable english string
// which resolves to "this is a tést"
Run Code Online (Sandbox Code Playgroud)
在获得可读格式的数据后,您可以使用NodeJS 中的fs模块存储它。
fs.writeFile('myFile.txt', "the contents of the file", (err) => {
if(!err) console.log('Data written');
});
Run Code Online (Sandbox Code Playgroud)
因此,在将缓冲输入转换为字符串后,您需要将字符串传递到writeFile方法中。您可以查看fs模块的文档。它将帮助您更好地理解事物。