我通过我的应用程序将图像文件发送到我的节点服务器-
我想将这些图像托管在Google云端或类似设备上,以便它们具有可访问的URL。
我已经尝试过使用cloudinary和google cloud,但到目前为止都无济于事!
我的反应方代码(缩短):
imageFile = this.state.files[0])
const formData = new FormData()
formData.append('file', imageFile);
sendImage(formData)
sendImage(image) {
axios.post("https://137a6167.ngrok.io/image-upload", image, {
})
.then(res => { // then print response status
console.log(res.statusText)
})
}
文件已成功发送到我的服务器并进行了控制台:
app.post('/image-upload', (req, res) => {
console.log('consoling the req.body!!!!' + JSON.stringify(req.body))
})
控制台:安慰请求正文!!!! {“ 1”:“ [目标文件]”}
我确实尝试过使用下面的cloudinary方法,但是它引发了错误:
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
})
app.use(formData.parse())
app.post('/image-upload', (req, res) => {
const values = Object.values(req.files)
const promises = values.map(image => cloudinary.uploader.upload(image.path))
Promise
.all(promises)
.then(results => res.json(results))
})
这给了我一个错误,即诺言中未处理的错误没有得到处理,我对超出该范围的地方感到迷茫!
我也查看了Google云存储,但无法正常运行!有什么建议吗?
我真正想做的是将托管图像的URL返回到我的react应用程序-以便可以将其存储在数据库中供用户使用!
如果您能提供所有帮助,将不胜感激,谢谢。
答案 0 :(得分:0)
在尝试上传到任何云之前,您需要在前端进行一些修复。
首先,您需要在'Content-Type': 'multipart/form-data'
中设置axios
标头以正确发送文件数据。
检查此线程以获取更多详细信息:How do I set multipart in axios with react?
然后在快速端,您需要multer
或其他类似的库来接收数据。您无法从req.body
访问它。 multer
添加req.files
。
https://github.com/expressjs/multer
尝试执行以下步骤,然后发布您从Google Cloud收到的确切错误消息。