Prevent Redirect on File Upload through form Submittal (React, Express, Multer)

前端 未结 3 1079
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 18:54

I\'m setting up a file uploading functionality for the first time. I have a react front-end and an express server that will store the files. I have it set up so a user can submi

相关标签:
3条回答
  • 2021-01-24 18:57

    Here is how I handle submitting files with 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);
    };
    

    The handleChange method is tied to the onChange event of the <input type="file" onChange={this.handleChange} />

    Then in the form submit handler

    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
        })
    };
    
    0 讨论(0)
  • 2021-01-24 18:58

    create a method in your Component that handles the submit, in the onSubmit attribute of your form call it like: onSubmit="{this.handleSubmit}" and post your data in an async way.

    0 讨论(0)
  • 2021-01-24 19:12

    In your submitForm handler, pass a reference to the event and use event.preventDefault().

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

    You can also try

    <form className="upload-form" ref="uploadForm" id="uploadForm" action="http://localhost:3050/upload" method="POST" enctype="multipart/form-data" onSubmit={ (event) => { event.preventDefault(); } }>
    
    0 讨论(0)
提交回复
热议问题