如何读取文件从传入的请求不保存到本地磁盘使用node.js express?



我的后端serverexpress(node.js)中,所有apis都在这个server上运行。我也有file-upload机制file-uploadapi使用multer。对于文件上传,我创建了一个middleware,在我的helpercontroller中,我有这个

const storage = multer.diskStorage({
destination: (req, file, cb) => {
let path = getFileStoragePath(req, file);
console.log(`path to create ${path}`)
// let path = `uploads/transId${req.body.refrenceId}/transporter`
checkDirectory(path, (err) => {
if (err) {
console.log(`Error occured if checkDirectory ${err.message}`)
cb(err, null)
} else {
cb(null, path);
}
});
},
filename: (req, file, cb) => {
let dateNow = new Date()
cb(null, `${file.fieldname}_${dateformat(dateNow, 'dddd_mmmm_dS_yyyy_h_MM_ss_TT')}${path.extname(file.originalname)}`)
}
});
const saveFilesToFolder = async(req, res, next) => {
const upload = multer({
storage: storage,
fileFilter: imageFilter,
limits: {
fileSize: 1024 * 1024 * 10
}
}).any();
upload(req, res, (err) => {
const wasValidRequest = checkAllowedFiles(req);
if (wasValidRequest.status === false) {
return res.send({
status: false,
message: wasValidRequest.message,
response: null
})
}
// counter = 0
if (err) {
console.log(`Error uploading files, ${err.message}`)
return res.send({
status: false,
message: `Error occurred while uploading files, ${err.message}`,
response: null
})
}
// WHEN FILE UPLOADING IS DONE NOW PASSING THE REQUEST
next();
});
};

在我的route.js文件中,我附加了middleware来保存files到文件夹中,并像这样读取files

router.post('/upload-files', saveFilesToFolder, catchAsyncErrors(fileController.UploadFiles));

但现在我的要求是,我想读取filecontent,这是在incoming request没有保存该文件到本地disk通过访问我的fileControllerfunction内的文件,我想为此目的做一个单独的api ?

我该怎么做呢

Multer提供了内存选项,通过该选项,我们可以不将文件存储在本地系统中,将其转换为缓冲区并读取内容。

参考this或this

var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.post('/imagenes', upload.single('image_field'), function(req,res){
req.file.buffer;
});

在控制器中可以使用

console.log(String(req.file.buffer))

查看内容

我的要求是在我的controller函数中使用multer中间件来从request传入access/read文件。所以我已经做到了,我正在给未来的读者一个答案,所以我喜欢这个

controller.js

var storage = multer.memoryStorage({
destination: function(req, file, callback) {
callback(null, '');
}
});
var upload = multer({ storage: storage }).any();

const saveFilesToS3 = async(req, res) => {
upload(req, res, async(err) => {
console.log(req.files[0].buffer) // printing incoming file content as buffer
// rest of the code here 
})
}

您不需要处理缓冲区,将缓冲区转换为文件需要完成另一项工作。你可以使用os.tmpdir()

const os = require('os');
const multerObject = multer({ dest: os.tmpdir() });
multerObject.single('file')

相关内容

  • 没有找到相关文章

最新更新