所以这是我第一次尝试将文件上传到服务器,我开始按照教程在 react 中构建后端和前端,但我无法让它工作。 我的后端现在正在进行一些调整,我一直在邮递员中尝试,我上传的文件最终进入上传文件夹。 但是当我用我的前端在浏览器中尝试它时,我无法让它工作,我只得到我的控制台.log字符串"msg 未上传文件",而不是后端的实际 msg。
有人能看到我写错的地方吗? 我已经将其与类似的代码进行了比较,我试图更改一堆东西,但我看不出为什么或缺少什么?
服务器.js
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const path = require("path")
var moment = require('moment')
const port = process.env.PORT || 5000
const app = express()
// enable files upload
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(fileUpload())
app.use(express.static('./public'));
//middlewares
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('hello world')
})
app.get('/upload', (req, res) => {
console.log('req.files.file', req.files.file)
res.json(req.files.file) //files should give the uploaded file
res.json(req.body.file) //body should give the name and description field
})
//Upload endpoint
app.post('/upload', (req, res) => {
try {
if (req.files === null) {
return res.status(400).json({ msg: 'No file uploaded' })
}
const file = req.files.file
const fileName = file.name
//const description = req.body
//const date = moment().add(10, 'days').calendar()
const extension = path.extname(fileName)
const allowedExtensions = /xml|jpeg|jpg|pdf/
if (!allowedExtensions.test(extension)) throw "Unsupported file type!";
//.mv() = move the file to current dir/client(react)/public
file.mv(`${__dirname}/client/public/uploads/${file.name}`)
res.json({
message: 'File uploaded successfully!',
fileName: file.name,
description: req.body,
date: moment().add(10, 'days').calendar(),
filePath: `/uploads/${file.name}`
})
} catch (err) { //catch if path doesn't exist
console.error(err)
//500 server error
return res.status(500).send(err)
}
})
//make uploads directory static
app.use(express.static('uploads'));
//Delete endpoint
//app.delete('/upload')
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})
文件上传.js
import React, { useState } from 'react'
import axios from 'axios'
const FileUpload = () => {
const [file, setFile] = useState('')
const [fileName, setFileName] = useState('Choose File')
const [uploadedFile, setUploadedFile] = useState({});
const onChange = (e) => {
setFile(e.target.files[0])
setFileName(e.target.files[0].name) //this should change the name in {fileName}
}
const onSubmit = async e => {
e.preventDefault()
const formData = new FormData()
formData.append('file', file)
console.log('file', file)
try {
const res = await axios.post('/upload', formData, {
header: {
'Content-Type': 'multipart/form-data'
}
})
const { fileName, filePath } = res.data
console.log('res.data', res.data)
setUploadedFile({ fileName, filePath })
console.log('setUploadedFile', fileName, filePath)
} catch (err) {
if (err.response.status === 500) {
console.log('There was a problem with the server')
} else {
console.log('msg No file uploaded', err.response.data.msg)
}
}
}
return (
<>
<form onSubmit={onSubmit}>
<div className='custom-file'>
<input
type='file'
name='file'
className='custom-file-input'
id='customFile'
onChange={onChange} />
<label
className='custom-file-label'
htmlFor='customFile'>{fileName}
</label>
</div>
<input
type='submit'
value='Upload file'
className='btn btn-secondary btn-block mt-4'
/>
</form>
{uploadedFile ? (
<div>
<h3>{uploadedFile.fileName}</h3>
<img scr={uploadedFile.filePath} alt='' />
</div>
) : null}
</>
)
}
export default FileUpload
后端服务器运行在端口 5000 上(假设您没有设置process.env.PORT
的变量(,因此 url 应该是http://localhost:5000
或http://127.0.0.1:5000
。
axios.post('/upload', ...)
正在将数据发布到反应 url。因此 404 错误。
const res = await axios.post('http://localhost:5000/upload', formData, {
header: {
'Content-Type': 'multipart/form-data'
}
})