我想要创建一个端点,它应该将文件存储在服务器端,以及应该从同一点接收的一些json数据将存储在mongodb上。我使用axios从React发送请求。这是我的密码。
const [companyFile, setCompanyFile] = useState(null);
const [company, setCompany] = useState({
name: "",
websiteUrl: "",
email: "",
companyLocation: "",
});
const AddCompany = async (e) => {
if (companyFile) {
e.preventDefault();
let formData = new FormData();
formData.append("company-file", companyFile);
formData.append("company", JSON.stringify(company));
axios({
method: "post",
url: `http://localhost:8080/company/add`,
data: formData,
withCredentials: true,
header: {
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((res) => console.log(res.data));
} else {
console.log("file not selected!!!!");
}
};现在我不知道如何检查它是否到达后端快车服务器?或者,如果来了,那么如何从请求中检索application/json数据以供进一步处理。
我的问题是,如果数据被发送到后端express,那么如何处理后端中的数据(即获取json数据以在mongodb中创建文档)。这是我的company/add代码
let upload = multer({
storage: multer.diskStorage({
destination: async (req, file, cb) => {
if (!company) {
throw Error("Company cannot be found!");
}
let companyName = req.company.name;
let path = `./uploads/${companyName}/files`;
if (!fs.existsSync(path)) {
fs.mkdirSync(path, { recursive: true });
}
cb(null, path);
},
filename: async (req, file, cb) => {
// ** with student auth Code
req.filename = req.company.name;
cb(null, filename + path.extname(file.originalname));
},
}),
}).single("company-file");
// Add Company
module.exports.add_company = async (req, res) => {
try {
// Here I want to extract that company object to create new company
console.log(req.file);
try {
const newcompany = await Company.create(company);
req.company = newcompany;
upload(req, res, async () => {
try {
const companyFile = await CompanyFile.create({
companyId: req.company._id,
path: `./uploads/${req.company.name}/file/${req.filename}.pdf`,
});
req.companyFile = companyFile;
} catch (err) {
res.status(400).json({ success: false, message: err.message });
// ** code for resume-upload using student authentication middleware
if (
fs.existsSync(
`./uploads/${req.company.name}/file/${req.filename}.pdf`
)
) {
fs.unlink(`./uploads/${req.company.name}/file/${req.filename}.pdf`);
}
}
});
res.status(201).json({
success: true,
message: "Company Drive Added Successfully.",
company: req.company,
companyFile: req.companyFile,
});
} catch (err) {
res.status(400).json({
success: false,
errors: err,
message: "Error while applying company drive.",
});
}
} catch (err) {
console.log(err);
}
};发布于 2022-08-20 07:05:05
来自文档
Multer向请求对象添加一个body对象和一个或多个文件对象。body对象包含表单文本字段的值,文件或文件对象包含通过表单上载的文件。
因此,在您的示例中,您可以通过以下操作访问和解析company字段:
const company = JSON.parse(req.body.company);此外,您还需要确保将multer中间件应用于您的控制器。
app.post('/company/add', upload.single('company-file'), function (req, res, next) {
// req.file is the `company-file` file
// req.body.company will hold the company text field
})https://stackoverflow.com/questions/73421542
复制相似问题