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?
In your submitForm handler, pass a reference to the event and use event.preventDefault().
You can also try
Here is how I handle submitting files with Axios
The handleChange method is tied to the onChange event of the
<input type="file" onChange={this.handleChange} />
Then in the form submit handler
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.