我目前正在尝试将多个文件池组件/实例集成到我的反应应用程序中,其中图像上传到按钮/表单提交。
我或多或少地使用下面的代码,但是当我在 routes.js 文件中注销结果时,我得到了一个未定义的结果,即使当我在 upload.js 中注销提交状态时,我确实得到了结果.
我试过只注销req.files,它返回未定义,我在下面使用的方法直接来自multers文档,这会注销-TypeError :无法读取未定义的属性'0'
谢谢
上传.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import "./styles.css";
import { FilePond, registerPlugin } from "react-filepond";
import "filepond/dist/filepond.min.css";
// import FilePondPluginFileEncode from 'filepond-plugin-file-encode';
import FilePondPluginImageExifOrientation from "filepond-plugin-image-exif-orientation";
import FilePondPluginImagePreview from "filepond-plugin-image-preview";
import "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css";
// Register the plugins
registerPlugin(FilePondPluginImageExifOrientation, FilePondPluginImagePreview);
const API_BASE = "http://localhost:5000";
function submitForm(contentType, data, setResponse) {
axios({
url: `${API_BASE}/upload`,
method: "POST",
data: data,
headers: {
"Content-Type": contentType
}
})
.then(response => {
setResponse(response.data);
})
.catch(error => {
setResponse("error");
});
}
function App() {
const [title, setTitle] = useState("");
const [file, setFile] = useState("");
const [file3, setFile3] = useState("");
const [desc, setDesc] = useState("");
function uploadWithFormData() {
const formData = new FormData();
formData.append("title", title);
formData.append("file", file);
formData.append("file3", file3);
formData.append("desc", desc);
submitForm("multipart/form-data", formData, msg => console.log(msg));
}
return (
<div className="App">
<h2>Upload Form</h2>
<form>
<label>
File Title
<input
type="text"
vaue={title}
onChange={e => {
setTitle(e.target.value);
}}
placeholder="Give a title to your upload"
/>
</label>
<FilePond
name={file}
files={file}
allowMultiple={false}
server={null}
instantUpload={false}
onupdatefiles={setFile}
/>
<FilePond
name={file3}
files={file3}
allowMultiple={false}
server={null}
instantUpload={false}
onupdatefiles={setFile3}
/>
<label>
Description
<textarea value={desc} onChange={e => setDesc(e.target.value)} />
</label>
<input
type="button"
value="Upload as Form"
onClick={uploadWithFormData}
/>
</form>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
路由.js
router.post('/', upload.fields([{ name: 'file'}, { name: 'file3' }]), (req, res) => {
console.log(req.files['file'][0]);
console.log(req.files['file3'][0]);
var movieData = {
desc: req.body.desc,
title: req.body.title,
imgCollection: req.files['file'],
poster: req.files['file3']
};
Movie.create(movieData)
.then(movie => res.json({ msg: 'Movie added successfully' }))
.catch(err => res.status(400).json({ error: 'Unable to add this movie' }));
});
控制台日志的图像