javascript - 将图像文件发送到 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})
}
})
解决方案
推荐阅读
- sql-server - 如何解析存储在 SQL Server 列中的 XML
- azure - API 访问 Azure 中的新磁盘 IO 和带宽指标
- java - java - 在 Java 中将 JSON 字符串拆分为 JSON 字符串
- mysql - 显示 SQL 查询的错误数据
- tuf - 如何在 AGL 平台上使用 aktualizr 进行 OTA 更新
- mongodb - Reg:聚合函数使用分组格式输出
- angular - PrimeNG p-calendar 不适用于 Spring Boot Rest API
- ios - iOS 14 在 NSFetchedResultsController 的 indexPathForObject 函数中崩溃
- php - 复选框数据处理
- javascript - 无法从电子视频聊天应用程序中的第二个窗口打开视频源(第一个窗口可以正常打开视频源)