gpt4 book ai didi

node.js - Multer 上传单曲在 ReactJS 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:24 25 4
gpt4 key购买 nike

我尝试了多个在线资源将文件上传到本地计算机上的目的地。此控制台显示文件已上传,但在目标文件夹中看不到该文件。这是我的 server.js 代码:

const app = express()
app.use(bodyParser())
app.set('view engine', 'hbs')
app.use(express.static(__dirname + '/public'))
app.set('views', __dirname + '/views')
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.get('/', (req, res) => {
res.render('index.hbs')
})

app.listen(port, () => {
console.log(`App is live on port ${port}`)
})

app.post('/upload', upload.single('myFile'), (req, res, next) => {

console.log('called')
console.log(req.body.myFile)

if (req.body.myFile) {
console.log('Uploading file...')
var filename = req.body.myFile

var uploadStatus = 'File Uploaded Successfully'
} else {
console.log('No File Uploaded')
console.log('======================== SESSION END ========================')
var filename = 'FILE NOT UPLOADED'
var uploadStatus = 'File Upload Failed'
}

/* ===== Add the function to save filename to database ===== */

res.render('index.hbs', { status: uploadStatus, filename: `Name Of File: ${filename}` })
})

这是我的index.hbs 文件:

<form action="/upload"  method="POST">
<input type="file" name="myFile" required />
<input type="submit" value="Upload" />
</form>

有人可以帮我解决这个问题吗?

最佳答案

这里的问题出在你的 hbs 上。表单缺少属性:enctype="multipart/form-data"

PS:req.body 应包含额外的数据(例如文本字段),要输出文件,您应检查req.file

一切都在文档中:https://github.com/expressjs/multer#readme

关于node.js - Multer 上传单曲在 ReactJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55002215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com