reactjs - REACT JS: send react object array to php
Solution:
Based on the names of your components, I assume that you want to upload files using ajax.
To upload files with ajax, you need to post FormData
instead of JSON objects.
Here is the code:
const handleUploader = (file)=>{
const fd = new FormData();
fd.append('file', file);
axios({
method: 'POST',
url: `https://url_to_backend`,
data: fd,
onUploadProgress: (progressEvent) => {
const uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log("uploadProgress",uploadProgress);
}
}).then(res => {
// after success
}).catch(err => {
// handle error
})
}
Answer
Solution:
In case this code is intended for real world use (production) I would advise using a library to take care of the client-side file upload. There are many factors and edge-cases to handle for it to work cross-browser and in different scenarios.
Can recommend react-uploady. You can use the grouped prop to allow multiple files in the same request:
import React from "react";
import Uploady from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
const App = () => (<Uploady
grouped
destination={{ url: "https://my-server/upload" }}>
<UploadButton/>
</Uploady>);
Source