我坚持显示我使用 multer-gridfs-storage 上传到 mongodb 的图像。
问题是,我应该在每个块中都有二进制数据,我想加入它们以制作最终文件并将其编码为 base64
mongodb 告诉它是二进制数据,但我不太确定 mongodb 块
这是我的代码:
multer.js:
const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const db = require("../utils/database").db;
const storage = new GridFsStorage({ db });
module.exports = {
upload: multer({
storage: storage,
})
};
我重新组装文件的功能:
const getImage = (fileName) => {
return files
.find({ filename: fileName })
.then((file) => {
const id = mongoose.Types.ObjectId(file[0]._id);
return chunks
.find({ files_id: id })
.then((chunks) => {
if (!chunks || chunks.length === 0) {
console.log("No data found");
}
let fileData = [];
for (let i = 0; i < chunks.length; i++) {
//This is in Binary JSON or BSON format, which is stored
//in fileData array in base64 endocoded string format
fileData.push(chunks[i].data.toString('base64');
}
//Display the chunks using the data URI format
return (finalFile =
"data:" + file[0].contentType + ";base64," + fileData.join(""));
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
};
我有这种结果 .toString('base64')
���R3\x17�\x18��bC4%\x19�rS5&��cDT6\'7\x1A�s�E���dUte�89\x11\x00\x02\x01\x02\x04\x03\x05\x07\x02\x04\x04\x05\x02\x03\x01\x11\x00\x01\x02\x11\x03!1\x12\x04AQ\x05aq"\x13\x06������2�\x07�B#\x14�R3\x15br$4\b�\x16���C%�S\x17D5&�c��s�Td6\t��\x00\f\x03\x01\x00\x02\x
并且没有 .toString('base64')
77+977+977+9DR7vv70D0IJO77+9NSVq0qEu77+9I++/vRl477+9D++/vS3vv70GUE7vv71H77+977+9UO+/vS8eKO+/vVLvv73vv73vv73vv73vv70d77+9XO+/vXjvv71t77+977+9f++/vW3vv73vv73vv73vv71Q77+977+9Nu+/vSVD77+977+977+9FXnvv70277+9d++/vRE3Zu+/vQcgST1P77+92orVle+/vX5lIu+/vVPvv70o77+9Cu+/ve+/vTvvv73bnu+/vR3vv70a77+9VEZqTu+/vXkR77+977+9cyjvv73vv70kVT/vv73vv73vv70Hbe+/vW3vv73oiJzvv71FeGtS77+9Xu+/ve+/vT9xWcSGAO+/ve+/ve+/ve+/ve+/vX3vv73vv73vv73vv73vv71zSsKcVF5VOw7vv73vv73vv71M77+9CGPvv73Mo++/ve+/vWDvv712Ie+/ve+/vXbvv71g77+9S++/ve+/vWJRWNGU77+977+9GSw5AO+/vRIzdu+/ve+/vQkb77+9Se+/vTrvv70277+977+977+977+977+977+9RVVn77
感谢您的帮助 !