首页 > 解决方案 > 使用 MongoDB、express、node 和 react 上传图片

问题描述

我一直在关注 YouTube 上的这个很棒的教程,试图建立一个网站。但是,一旦我部署它,图像就不会显示,因为目前它们都保存在一个名为 uploads 的本地文件夹中。这就是它现在的样子:

服务器端

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/')
    },
    filename: (req, file, cb) => {
        cb(null, `${Date.now()}_${file.originalname}`)
    },
    fileFilter: (req, file, cb) => {
        const ext = path.extname(file.originalname)
        if (ext !== '.jpg' || ext !== '.png') {
            return cb(res.status(400).end('only jpg, png are allowed'), false);
        }
        cb(null, true)
    }
})

var upload = multer({ storage: storage }).single("file")

router.post("/uploadImage", auth, (req, res) => {

    upload(req, res, err => {
        if(err) return res.json({success: false, err})
        return res.json({ success: true, image: res.req.file.path, fileName: res.req.file.filename})
    })
   
});

CLIENT SIDE:图像字段存储一个字符串(即“uploads\xxxxxxxx.jpg”)

function ProductImage(props) {

    const [Image, setImage] = useState();

    useEffect(() => {
        setImage(`http://localhost:5000/${props.detail.image}`)
        

    }, [props.detail])
    
    return(
        <div>
            <img style={{maxWidth: '30vw'}} 
            src={Image} alt="productImg"/>
        </div>
    )
}

所以我想我现在的问题是如何将图像实际上传到 MongoDB,以及如何检索它们?

标签: node.jsreactjsmongodbexpressmulter

解决方案


如果您将上传的图像存储在 Heroku 服务器中,这完全是一种浪费。因为 Heroku Dyno 将每天重新启动,这将删除所有额外添加的数据,而不是在部署期间存储的数据。

要先上传到 MongoDB,您需要将其存储到服务器,multer 完成该工作,稍后它将自动从 heroku 中删除。下面的代码加密您的数据并根据 id 将其上传到特定文档。

//Hashing and uploading to Mongodb 
fs.readFile('your file location', async function (err, data) {
    if (err) {
        console.log(err)
    } else {
        let iv = crypto.randomBytes(16);
        let pass = //I think 32 char password is required
        let cipher = crypto.createCipheriv('aes-256-ctr', pass, iv)
        let crypted = Buffer.concat([iv, cipher.update(data), cipher.final()]);


        console.log("crypted", crypted);
        let dataa = await User.findOne({
            _id: "Id of a MongoDB document"
        })
        //let buffer=new Buffer(data)
        dataa.files.push(crypted)
        await dataa.save()
        console.log("done")
    }

});

检索和解密数据

let data = await User.findOne({
    _id: "id of a MongoDB document"
})
console.log("dattttt", data.files[index of your image in mongoarray].buffer)


iv = data.files[index of your image in mongoarray].buffer.slice(0, 16);
chunk = data.files[index of your image in mongoarray].buffer.slice(16);
var decipher = crypto.createDecipheriv('aes-256-ctr', "same 32 char password here", iv)
var dec = Buffer.concat([decipher.update(chunk), decipher.final()]);

console.log("dec", dec);
let buffer = new Buffer.from(dec)
console.log("buffer", buffer)
fs.writeFile(`downloadable file location/filename.extension`, buffer, "binary", function (err, written) {
    if (err) console.log(err);
    else {
        console.log("Successfully written");
        res.sendFile((__dirname + `downloaded file location/filename.extension`))
    }
});

推荐阅读