当我从 Mongodb 加载图像时,收到此错误 data:image/png;base64,[object Object]

问题描述 投票:0回答:1

我有一个 html 表,我在其中从 MongoDB 获取数据,但图像拒绝显示,我不确定我做错了什么。

这是我到目前为止所做的。

这是从客户端获取图像和数据并发送到后端服务器的js代码

app.post('/newInt_ImgUpload', upload.array('inventoryImg', 3), async (req, res) => {
    //console.log(req.files);
    //console.log(req.body);
    const cookies = req.headers.cookie;
    const jwtToken = cookies.split("=")[1].split(";")[0];
    //console.log(jwtToken);
    if (!jwtToken) {
        console.log('app crashed at line 119: PersonalInfo');
        return res.sendStatus(401);
    }
    const refreshToken = jwtToken;

    const user = await userModel.findOne({RefreshToken: refreshToken}).exec()
    if(!user) return res.sendStatus(401);
    console.log('User was found');

    const count = new Uint32Array(1);

    try {
        const inventory = await inventoryModel.create({
            'UserId': user._id,
            'Name': req.body.ItemName,
            'DateAdded': date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[0],
            'Price': req.body.Price,
            'WeightKG': req.body.WeightKG,
            'Quantity': req.body.Quantity,
            'Description': req.body.Description,
            'image1': { 
                data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[0].filename)).toString('base64'),
                contentType: req.files[0].mimetype
            },
            'image2': { 
                data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[1].filename)).toString('base64'),
                contentType: req.files[1].mimetype
            },
            'image3': { 
                data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[2].filename)).toString('base64'),
                contentType: req.files[2].mimetype
            },
            'Id': Math.trunc((crypto.getRandomValues(count))/1000000)
        });
        const result = await inventory.save();
        console.log(result);
        const inventoryActivitylog = await activityLogsModel.create({
            'UserId': user._id,
            'Date': date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[0],
            "Time": date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[1],
            'Status':  "Inventory updated."
        });
        await inventoryActivitylog.save();

        req.files.forEach(files => {
            fs.unlink(path.join(__dirname + '/uploads/' + files.filename), (err) => {
                if (err) throw err;
                //console.log('Image deleted');
              });
        })
        console.log("All images deleted")
        //res.redirect('/userProfile');
        res.status(200).json({ success: true, message: 'Inventory updated and images processed' });
    } catch (error) {
        console.log(error);
    }
});

完成后,下面的代码每次都会加载到显示表格数据的页面,但图像拒绝显示并给出以下错误:data:image/png;base64,[object Object]

document.getElementById('allitems').addEventListener('click', async () => {
    try {
        const response = await fetch('http://localhost:4000/Inventory/allInventory/List', { 
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include' 
        })

        .then(async response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`); 
            }
            return response.json();
            })
        .then(data => {
            const inventoryList = document.querySelector('.inventoryList');
        
            // Clear any existing rows
            inventoryList.innerHTML = '';

            // Loop through the fetched data and create new rows
            data.forEach(item => {
                console.log(item);
                const eachInventory = document.createElement('div');
                eachInventory.classList.add('eachInventory');

                const imgsrc = `data:${item.image1.contentType};base64,${item.image1.data}`;

                eachInventory.innerHTML = `
                    <div class="itemName">
                        <div><img src="${imgsrc}" alt=""></div>
                        <div><h4>${item.Name}</h4></div>
                    </div>
                    <div class="itemDate"><h3>${new Date(item.DateAdded).toLocaleDateString()}</h3></div>
                    <div class="itemPrice"><h3>${item.Price.toLocaleString()}</h3></div>
                    <div class="itemQuantity"><h3>${item.Quantity}</h3></div>
                `;
                
                // Append the new row to the table
                inventoryList.appendChild(eachInventory);
            })
        });
    } catch (error) {
        console.error('Error:', error);
    }
});
javascript html mongodb multer
1个回答
0
投票

您的图像以 Base64 格式保存。与其将文件存储在数据库中,不如将其存储在任何外部服务中。如果您使用 AWS,您可以使用 s3 存储桶,如果不使用 s3,您可以尝试 cloudflare 图像服务、cloudinary 等。

© www.soinside.com 2019 - 2024. All rights reserved.