Is there a way to send an array of images (or a single image) to node using axios?
The axios code I'm using(I'm using react js on the front end):
onFormSubmit(event){ event.preventDefault(); let payload = this.state; console.log("in onFormSubmit!!! with state: ", this.state, "and payload: ", payload); axios.post('/api/art', payload) .then(function(response){ console.log('saved successfully') });
The research I've done suggests that perhaps there isn't a supported way to send image files to node using axios, but this seems strange to me. Is there a way?
First, you create a local React state selectedFile using useState() hook to store the currently selected file, Second, the handleFileSelect event handler updates the selectedFile value using the setter function setSelectedFile and, Third, the handleSubmit function handles the post request to upload file using Axios.
Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.
Here is the way I got this to work properly. I had to make use of an object called FormData. I used the import:
import FormData from 'form-data'
Of course before this import I had to run the npm install for it:
npm install --save form-data
Once I did all that, here is how I used it within my action:
let data = new FormData(); data.append('file', file, file.name); return (dispatch) => { axios.post(URL, data, { headers: { 'accept': 'application/json', 'Accept-Language': 'en-US,en;q=0.8', 'Content-Type': `multipart/form-data; boundary=${data._boundary}`, } }) .then((response) => { //handle success }).catch((error) => { //handle error }); };}
The important pieces to note here are:
Hope this helps, this cleared up all of the issues I had with trying to submit an image to a backend (in my case a rest service - through a post call).
Yes you will have to set the content type in your axios request:
axios.put(url, imageFile, { headers: { 'Content-Type': imageFile.type } });
where imageFile
is an HTML5 file object which should be an image in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With