无法使用 Fetch 从 React 前端发送文件到 Express 4 API
Trouble sending File from React frontend with Fetch to Express 4 API
我正在尝试将图像文件从我的 React 前端发送到我的 express API:
fetch('http://localhost:4000/upload/', {
method: 'POST',
body: this.state.picture[0],
})
当我记录文件时,该文件在 chrome 控制台中看起来是正确的:
File {name: "31-614x614.jpg", lastModified: 1553111550472, lastModifiedDate: Wed Mar 20 2019 12:52:30 GMT-0700 (Pacific Daylight Time), webkitRelativePath: "", size: 95101, …}
但是,当我尝试在后端的请求中记录文件时,根据我的设置方式,我得到未定义或空的请求对象。
我试过使用类似堆栈溢出问题中推荐的 multer、busboy 和 express-fileupload,但遇到了同样的问题。
这是我的路由器:
const Router = require('express').Router();
const imgController = require('./controllers/imgController');
Router.get('/images/', imgController.getImages);
Router.post('/upload/', imgController.postImage);
module.exports = Router;
我只是想查看正在发送的文件的控制器:
exports.postImage = (req, res) => {
console.log("IN POST IMAGE")
console.log(req.body)
console.log(req.files)
}
我确实进入了控制器,但请求从未包含文件。
感谢您的帮助!
您是否尝试过构建 formData 元素并发送它?
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
我正在尝试将图像文件从我的 React 前端发送到我的 express API:
fetch('http://localhost:4000/upload/', {
method: 'POST',
body: this.state.picture[0],
})
当我记录文件时,该文件在 chrome 控制台中看起来是正确的:
File {name: "31-614x614.jpg", lastModified: 1553111550472, lastModifiedDate: Wed Mar 20 2019 12:52:30 GMT-0700 (Pacific Daylight Time), webkitRelativePath: "", size: 95101, …}
但是,当我尝试在后端的请求中记录文件时,根据我的设置方式,我得到未定义或空的请求对象。
我试过使用类似堆栈溢出问题中推荐的 multer、busboy 和 express-fileupload,但遇到了同样的问题。
这是我的路由器:
const Router = require('express').Router();
const imgController = require('./controllers/imgController');
Router.get('/images/', imgController.getImages);
Router.post('/upload/', imgController.postImage);
module.exports = Router;
我只是想查看正在发送的文件的控制器:
exports.postImage = (req, res) => {
console.log("IN POST IMAGE")
console.log(req.body)
console.log(req.files)
}
我确实进入了控制器,但请求从未包含文件。 感谢您的帮助!
您是否尝试过构建 formData 元素并发送它?
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})