我的流程和代码:
从表单数据上传图像并将图像的BSON字符串存储到数据库,以下是步骤和代码:
-
从multer上传上传文件
-
从文件系统读取文件-fs
-
将图像内容字符串转换为base64字符串
-
将base64字符串转换为BSON字符串
配置:
node -v: v12.13.1
npm -v: 6.12.1
fs-extra: ^8.1.0
multer: ^1.4.2
代码:
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
});
upload.single('picture'), (req, res) => {
let imageString = fs.readFileSync(req.file.path);
let encodeImage = imageString.toString('base64');
let bufferImage = Buffer.from(encodeImage, 'base64');
var finalObj = {
contentType: req.file.mimetype,
image: bufferImage
};
db.collection('filesUpload').insertOne(finalObj, (err, result) => {
if (err) {
console.log(err);
}else{
console.log('success');
}
});
});
什么在起作用?
我可以成功上传16MB以下的图像,并可以从数据库中正确读取和检索。
什么不起作用?
我无法上传16MB以上的图片。
错误:
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 && <= 17825792. Received 18646861
at Buffer.write (buffer.js:1019:5)
at serializeObjectId (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\parser\serializer.js:274:14) at serializeInto (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\parser\serializer.js:935:17)
at serializeObject (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\parser\serializer.js:347:18)
at serializeInto (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\parser\serializer.js:727:17)
at serializeObject (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\parser\serializer.js:347:18)
at serializeInto (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\parser\serializer.js:941:17)
at BSON.serialize (D:\api\node_modules\mongodb\node_modules\bson\lib\bson\bson.js:64:28)
at Msg.serializeBson (D:\api\node_modules\mongodb\lib\core\connection\msg.js:126:22)
at Msg.makeDocumentSegment (D:\api\node_modules\mongodb\lib\core\connection\msg.js:118:33)
at Msg.toBin (D:\api\node_modules\mongodb\lib\core\connection\msg.js:104:25)
at serializeCommand (D:\api\node_modules\mongodb\lib\core\connection\pool.js:779:41)
at Pool.write (D:\api\node_modules\mongodb\lib\core\connection\pool.js:927:3)
at _command (D:\api\node_modules\mongodb\lib\core\wireprotocol\command.js:128:10)
at command (D:\api\node_modules\mongodb\lib\core\wireprotocol\command.js:28:5)
at writeCommand (D:\api\node_modules\mongodb\lib\core\wireprotocol\write_command.js:47:3) {
code: 'ERR_OUT_OF_RANGE'
}
我不知道如何解决这个问题,我认为是MongoDB错误,谢谢你的帮助。