首页 > 解决方案 > 将图像文件发送到 API Rest node.js

问题描述

我正在尝试制作一个接收图像并将其上传到 firebase 存储的 API REST。

我创建了一个名为 postImage 的端点来获取图像并上传它。

问题是我不知道如何传递图像。如果我像这样传递文件,则只有文件的几个字段到达服务器(但不是图像的字节)

const test = async (image) => {
    const response = await fetch("http://...", {
        method: "POST",
        body: image
    })
    const data = await response.json()
}

我试过使用 formData 但问题是在服务器上我只得到一堆我不知道如何使用的字节

const test = async (image) => {
    const fd = new FormData();
    fd.append('image', image);

    const response = await fetch("http://...", {
        method: "POST",
        body: fd
    })
    const data = await response.json()
}

这是服务器的代码。

它获取图像并将其上传到 Firebase 存储

router.post('/hello', async (req, res) => {
    try {
        const image = req.body;
        
        await firebase.storage().ref('photo/' + v4()).put(image, {
            contentType: 'image/jpeg',
        })

        return res.status(200).json({image: image})
    }
    catch(error) {
        console.log(error)
        return res.status(500).json({error})
    }
})

标签: javascriptfirebaseapiexpressfirebase-storage

解决方案


推荐阅读