我构建了一个基本的浏览器表单,允许用户上传PDF文件。然后,我想将该文件发送到Express后端。这似乎是一个非常基本的行动,但我不熟悉端到端的过程,所以我不确定哪一部分失败了。我已经搜索了许多这样的问题/答案,但没有找到一个完整的解决方案,我也无法拼凑出一个解决方案。
更新:--看起来文件正在到达服务器,但编码却搞砸了。我猜FileReader.readAsText是错误的使用方法。FileReader.readAsBinaryString让我离得更近了一点,但仍然不太正确(这是不推荐的)。FileReader.readAsArrayBuffer似乎是可行的方法,但我不知道如何正确处理Express中的缓冲区。
Client/Browser
表单是在React中构建的,只在输入本身上使用onChange处理程序。添加文件后,处理程序读取文件,将其添加到表单数据中,并将post请求发送到服务器。
// React form
<input
name="upload"
onChange={this._handleUpload}
type="file"
/>
_handleUpload = (e) => {
const { files, name } = e.target;
// Read the file
const reader = new FileReader();
reader.onload = (e) => {
const file = e.target.result;
// Now that we have the file's contents, append to the form data.
const formData = new FormData();
formData.append('file', file);
formData.append('type', name);
axios
.post('/upload', formData)
.then(res => {
// Handle the response...
})
.catch(err => console.log(err));
};
// Reading as text. Should this be something else?
reader.readAsText(files[0]);
}速递应用程序
快速应用程序使用穆特中间件处理上传:
const app = express();
const upload = multer({});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.post('/upload', upload.any(), handleUpload);中间件
最后,我有自己的中间件从multer那里获取文件。我只是把收到的文件写到磁盘上来测试这篇文章。它有内容,但它不是一个可读的PDF文件。
const handleUpload = (req, res, next) => {
// The file shows up on req.body instead of req.file, per multer docs.
const { file } = req.body;
// File is written, but it's not a readable PDF.
const tmp = fs.writeFileSync(
path.join(__dirname, './test.pdf'),
file,
);
}有什么地方我明显错了吗?PDF需要以一种特殊的方式处理吗?关于我的调试重点在哪里,有什么建议吗?
发布于 2018-12-15 01:55:24
看看这是否解决了你的问题.
_handleUpload = (e) => {
const dataForm = new FormData();
dataForm.append('file', e.target.files[0]);
axios
.post('http://localhost:4000/test', dataForm)
.then(res => {
})
.catch(err => console.log(err));
}
render() {
return (
<div className="App">
<input
onChange={this._handleUpload}
type="file"
/>
</div>
)
}服务器:
router.post('/test', upload.any(), (req, res) => {
console.log(req.files)
res.send({sucess: true})
})不需要发送文件类型,multer为您标识名称和类型。
https://stackoverflow.com/questions/53788528
复制相似问题