Prevent Redirect on File Upload through form Submi

2019-03-04 02:59发布

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 submit the file and it is saved the way I'd like it to be saved on the express server. However, whenever a user submits the form they are redirected from the react frontend (on port 3000) to the POST route on the server (port 3050). I didn't know that this was default behavior for a post request, which I expected would keep the users on the page.

I'd like to avoid this behavior but am unsure of the best way to go about it. I've tried building an action that functions as an AXIOS request, but am having trouble accessing the form data (particularly the file data) in the AXIOS request. My understanding is that there isn't native support for multipart form-data in AXIOS.

Event.preventdefault is the obvious choice, but any implementation of that stops the form submittal from grabbing the appropriate form data and sending it through.

The code for the form is included below (this version is using an on-click event that prevents the event default and dispatches the action - the action fires but as noted doesn't pass any of the relevant information through):

        <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>;

My simple Multer route:

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

My understanding is that there is no native support for sending a multipart-form item through Axios, I'd like to avoid pulling in a FormData module in order to make it work since the form (other than the redirect) works flawlessly. Is there a simple solution here that will prevent the form from trying to load the server-side page while still submitting the form data?

3条回答
Melony?
2楼-- · 2019-03-04 03:40

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(); } }>
查看更多
Root(大扎)
3楼-- · 2019-03-04 03:49

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
    })
};
查看更多
再贱就再见
4楼-- · 2019-03-04 03:49

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.

查看更多
登录 后发表回答