如何在 Express API 回调中上传文件?
How to upload file within Express API callback?
我知道如何使用 multer
将文件从客户端上传到 Express 服务器。
但是,这只能使用中间件功能来完成。
我正在寻找一种从 Express 回调中上传文件的方法 API。
我的用例是这样的:
客户上传包含图片 URL 的 CSV 文件。
我将从给定的 URL 下载这些图像
然后我会在 Express API 回调
中将这些图片上传到 MongoDb
(我正在寻找如何进行第 3 步。)
像这样:
app.post('/uploadtoDB',multer.single('file'),(req,res)=>{
let urls = parseCSV_and_GetUrls(req.file);
urls.forEach((url)=>{
downloadImage(url)
});
//Scan directory to get downloaded images
let stream = fs.createReadStream('/path/to/downloadedFile');
//Upload the downloaded image to MongoDb
uploadfile_to_MongoDB(stream);
})
我不建议直接在 MongoDB 中存储图像。建议将它们存储在静态文件存储 (S3) 中,并将 url/reference 保留在 MongoDB.
中
如果您确实想将其存储在MongoDB中,您可以将图像转换为 base64 编码的字符串。请注意,使用此方法时,您需要确保生成的文档小于 16 MB,因为 max. allowed doc size.
const fs = require('fs');
async function storeFileAsBase64EncodedString(pathToFile) {
const buffer = await fs.promises.readFile(pathToFile);
await db.collection('yourCollection').insertOne({ image: buffer.toString('base64') });
}
另一种选择是使用 GridFs,有关详细信息,请参阅 this。
我知道如何使用 multer
将文件从客户端上传到 Express 服务器。
但是,这只能使用中间件功能来完成。
我正在寻找一种从 Express 回调中上传文件的方法 API。
我的用例是这样的:
客户上传包含图片 URL 的 CSV 文件。
我将从给定的 URL 下载这些图像
然后我会在 Express API 回调
中将这些图片上传到 MongoDb
(我正在寻找如何进行第 3 步。)
像这样:
app.post('/uploadtoDB',multer.single('file'),(req,res)=>{
let urls = parseCSV_and_GetUrls(req.file);
urls.forEach((url)=>{
downloadImage(url)
});
//Scan directory to get downloaded images
let stream = fs.createReadStream('/path/to/downloadedFile');
//Upload the downloaded image to MongoDb
uploadfile_to_MongoDB(stream);
})
我不建议直接在 MongoDB 中存储图像。建议将它们存储在静态文件存储 (S3) 中,并将 url/reference 保留在 MongoDB.
中如果您确实想将其存储在MongoDB中,您可以将图像转换为 base64 编码的字符串。请注意,使用此方法时,您需要确保生成的文档小于 16 MB,因为 max. allowed doc size.
const fs = require('fs');
async function storeFileAsBase64EncodedString(pathToFile) {
const buffer = await fs.promises.readFile(pathToFile);
await db.collection('yourCollection').insertOne({ image: buffer.toString('base64') });
}
另一种选择是使用 GridFs,有关详细信息,请参阅 this。