防止通过表单提交(React、Express、Multer)重定向文件上传

IT技术 reactjs express file-upload
2021-05-20 01:48:49

我是第一次设置文件上传功能。我有一个react前端和一个将存储文件的快速服务器。我对其进行了设置,以便用户可以提交文件,并按照我希望将其保存在快速服务器上的方式进行保存。但是,每当用户提交表单时,他们都会从 react 前端(端口 3000)重定向到服务器上的 POST 路由(端口 3050)。我不知道这是发布请求的默认行为,我希望它能让用户留在页面上。

我想避免这种行为,但不确定最好的方法。我已尝试构建一个用作 AXIOS 请求的操作,但在访问 AXIOS 请求中的表单数据(尤其是文件数据)时遇到问题。我的理解是 AXIOS 中没有对多部分表单数据的本机支持。

Event.preventdefault 是显而易见的选择,但任何实现都会阻止表单提交获取适当的表单数据并将其发送。

表单的代码包含在下面(此版本使用点击事件来防止事件默认并分派动作 - 动作触发但如上所述不会传递任何相关信息):

        <div className="modal-wrapper">
            <h3 className="title__h3">Upload Data</h3>
            <p>Drag and drop anywhere or choose a file to upload.</p>
            <p>.csv or .xlsx</p>
            <form className="upload-form" ref="uploadForm" id="uploadForm" action="http://localhost:3050/upload" method="POST" enctype="multipart/form-data">
                <input name="fileName" placeholder="Name the file you're uploading here"/>
                <input type="file" name="upl" id="file" className="inputfile" />
                <label htmlFor="file" className="btn btn__white-outline btn__full-width">Select a File</label>
                <input onClick={this.submitForm} type="submit" value="submit" />
            </form>
        </div>;

我的简单 Multer 路线:

app.post('/upload', upload.single('upl'), function(req,res,next) {
  return false
})

我的理解是没有本地支持通过 Axios 发送多部分表单项,我想避免拉入 FormData module以使其工作,因为表单(重定向除外)可以完美地工作。这里是否有一个简单的解决方案可以防止表单在提交表单数据的同时尝试加载服务器端页面?

3个回答

在您的 submitForm 处理程序中,传递对事件的引用并使用 event.preventDefault()。

    submitForm(event) {
        event.preventDefault();
        ...other code here...
    }

你也可以试试

<form className="upload-form" ref="uploadForm" id="uploadForm" action="http://localhost:3050/upload" method="POST" enctype="multipart/form-data" onSubmit={ (event) => { event.preventDefault(); } }>

这是我如何使用 Axios 处理提交文件

handleChange = ( event ) => {
    const fileReader = new FileReader();
    const fileToUpload = event.target.files[0];

    fileReader.onload = ( upload ) => {
        const allFiles = [ ...this.state.allFiles ].concat( upload.target.result );

        this.setState({ 
            allFiles
        });
    };

    fileReader.readAsDataURL(fileToUpload);
};

handleChange 方法绑定到 onChange 事件 <input type="file" onChange={this.handleChange} />

然后在表单提交处理程序中

handleSubmit = ( event ) => {
    event.preventDefault(); //So the page does not refresh
    const { allFiles } = this.state;
    const Promises = [];

    allFiles.forEach( file => {
        Promises.push( Axios({
            url: "a url goes here",
            method: "POST",
            data: {
                file: file, //This is a data url version of the file
            }
        }));    
    });

    Axios.all(Promises).then( result => {
        alert(result.message); //Display if it uploaded correctly
    })
};

在您的组件中创建一个处理提交的方法,在onSubmit您的表单属性中调用它,例如:onSubmit="{this.handleSubmit}"并以异步方式发布您的数据。