我想读取图像,将其写入文件夹中,然后再次读取以获得base64 我收到以下错误: 错误:ENOENT:没有此类文件或目录,请访问“ C:\ Workspace \ Project \ upload_storage \ image.jpg” 在Object.accessSync(fs.js:192:3)
我的代码:
const FS = require("fs");
var multiparty = require('multiparty');
var path = require('path');
function readAndWriteFile(file , newPath){
FS.readFileSync(file.path, (err, data)=>{
FS.writeFileSync(newPath, data, (err)=>{
});
});
}
function base64Encode(path,filemime) {
FS.readFileSync(path, {encoding: 'base64'}, (err, data)=>{
if (err) {
throw err;
}
return `data:${filemime};base64,${data}`;
});
}
...
var form = new multiparty.Form()
//retrieve files using multiparty form
form.parse(req, function(err, fields, files) {
var document;
const documents = files.file;
for(i=0; i<documents.length; i++){
document=documents[i];
const contentType = String(document.headers["content-type"]);
filePath = path.join(process.cwd(),'/upload_storage/',document.originalFilename);
readAndWriteFile(document,filePath);
// // convert image to base64 encoded string
const base64str = base64Encode(filePath, contentType);
console.log(base64str);
}
}
如果我注释base64Encode函数调用,则会创建文件。 我在做什么错了?
答案 0 :(得分:0)
请勿对_fileSync
使用回调。但无论如何,您似乎都想copyFileSync
后跟unlinkSync
:
const fs = require('fs');
function readAndWriteFile(file , newPath){
fs.copyFileSync(file.path, newPath);
fs.unlinkSync(file.path)
}
您是否尝试过阅读fs
的文档?