Update
这是因为Creact React App附带了热重新加载 . 相关问题:https://github.com/expressjs/multer/issues/566
https://github.com/facebook/create-react-app/issues/4095
我正在尝试使用Nodejs,Express,Multer和React来学习文件上传 . 我实现了上传文件 . 有一个问题我很难,但并不总是,但大多数时候整个应用程序上传后刷新 . 这是相关的代码 .
My simple form
<form onSubmit={this.handleFormSubmit}>
<input
type="file"
id="file"
onChange={this.handleFileChange}
/>
<button type="submit">Submit</button>
</form>
handleFileChange and handleFormSubmit
handleFormSubmit = () => {
const formData = new FormData();
formData.append( "file", this.state.file );
axios.post( "/api/upload", formData );
}
handleFileChange = ( e ) => {
this.setState( { file: e.target.files[ 0 ] } );
}
Related express route code
const express = require( "express" );
const multer = require( "multer" );
const storage = multer.diskStorage( {
destination( req, file, cb ) {
cb( null, "client/public/images" );
},
filename( req, file, cb ) {
cb( null, `${ Date.now() }-${ file.originalname }` );
},
} );
const upload = multer( { storage } );
router.post( "/upload", upload.single( "file" ), ( req, res ) => {
res.send();
} );
我搜索了一下但没有运气 . 我见过this post . 在看到这个之前,我已经尝试过event.preventDefault() . 此外,我尝试过许多事情,例如直接使用onChange()上传而不设置状态,然后使用onSubmit()处理它 . 在简化代码之前(比如直接在handleFormSubmit中发布)我试图通过Redux操作来做这件事,但出于调试目的,我把它移到了这里 .
2 回答
这是第一个例子here .
你正在使用
这就是为什么要提神
所以这样做吧