【发布时间】:2022-02-13 03:16:56
【问题描述】:
我试图简单地将单个文件从客户端 (react/axios) 上传到服务器 (multer / express)。我已经阅读了每一个“req.file undefined”,但我自己的代码似乎看不到同样的问题。
另一个问题是实际上我在服务器上的 req 在“文件”中看到了该文件,但 multer 没有保存它并且 req.file 未定义。
这里会发生什么?
对于客户端,我尝试了两种发送表单数据的方法,但都不起作用。
const onAnalyze = async () => {
if (selectedFile !== null) {
//we have a file, so that's what we're sending
var formData = new FormData();
formData.append("analyze", selectedFile);
//let res = await api.post('/analyze/upload', formData)
try {
const response = await axios({
method: "post",
url: "http://localhost:5000/analyze/upload",
data: formData,
header: { "Content-Type": "multipart/form-data" }
});
console.log(response)
} catch (error) {
console.log(error)
}
// console.log(res)
// setAnalysis(res.data)
} else if (text.length <= maxLength) {
let res = await api.post('/analyze', { text: text })
setAnalysis(res.data)
}
}
对于服务器来说,这似乎很简单.. 我只是不知道。此文件目标存在。 req.file 始终未定义
import express from 'express';
import { getMedia, createMedia } from '../controllers/media.js';
import { AnalyzeText, AnalyzeFile } from '../controllers/analyze.js'
import multer from 'multer'
const fileStorageEngine = multer.diskStorage({
destination: "uploads",
filename: (req, file, cb) => {
cb(null, file.originalname)
}
});
var upload = multer({ storage: fileStorageEngine })
const router = express.Router();
//Get All Movies and TV shows.
router.get('/', getMedia);
//Request to create a new item based on a title
router.post('/', createMedia);
//Recuist to analyze information (not sure if this should be a post or not)
router.post('/analyze', AnalyzeText)
router.post('/analyze/upload', upload.single('analyze'), (req, res) => {
console.log(req.file)
res.status(200).json('well we found it again');
});
【问题讨论】:
标签: express file-upload axios multer