我正在尝试将文件从前端index.html发布到在后台运行的Express Server。然后,该API应该将文件保存到Firebase存储中。服务器正常运行,正在接收POST,但req.body中没有数据。
index.html-前端
<form method="POST" id="form">
<input type="file" id="file" name="file" multiple>
<input type="submit">
</form>
<script>
const form = document.querySelector('#form')
const postFile = (e) => {
e.preventDefault()
const header = { "Content-Type": "multipart/form-data" }
let formData = new FormData()
formData.append('file', this.file.files[0])
fetch('http://localhost:3003/file', {
method: form.method,
headers: header,
body: formData
}).then(() => {
alert("OK")
}).catch(() => {
alert("Nope")
})
}
form.addEventListener('submit', (e) => postFile(e))
</script>
server.js-后端(不完整)
const server = express()
const routes = require('./routes')
server.use(cors())
server.use(express.urlencoded({
limit: '50mb',
extended: true
}))
server.use(express.json({
limit: '50mb',
extended: true
}))
server.use(routes)
server.listen(3003)
fileController.js-后端(不完整)
exports.addFile = async (req, res) => {
try {
console.log(req.body)
return res.status(200).send({
message: "Ok"
})
} catch (e) {
return res.status(500).send({
message: e.message
})
}
当我在获取console.log(this.file.files [0])之前,它实际上会按预期返回文件,但是在服务器中只是一个空数组。Front-end console.log;Server console.log
确定,问题解决了。正如Wezelkrozum所指出的,我可以使用multer(npm install --save multer
)
已应用更改:
index.html
<form method="POST" id="form" **enctype="multipart/form-data"**>
<input type="file" id="file" name="file" multiple>
<input type="submit">
</form>
<script>
const form = document.querySelector('#form')
const postFile = (e) => {
e.preventDefault()
let formData = new FormData()
formData.append('file', this.file.files[0])
fetch('http://localhost:3003/file', { //Removed the Headers
method: form.method,
body: formData
}).then(() => {
alert("OK")
}).catch(() => {
alert("Nope")
})
}
form.addEventListener('submit', (e) => postFile(e))
</script>
routes.js
const express = require('express')
const multer = require('multer')
const routes = express.Router()
const upload = multer({dest: 'uploads/'}) //Folder where the file is stored
routes.post('/file', upload.single('file'), fileController.addFile) //This is for one file only
module.exports = routes
然后在Controller中,文件将作为req.file出现,就像:
let file = req.file