=> If only the data has to be sent through axios then we can directly use axios.METHOD to send the data to any URL
=> But if only the image/file has to be uploaded or along with data then we must use XMLHttpRequest to send the data+files/images using FormData()
=> Just append the image/file to be sent to formData and we are ready to go.
Point to be Noted
- // params received in functions are: URL, METHOD, DATA, FILES, fieldName, isSecure=false
- // Inside the body we must write all the code with return new Promise((resolve, reject) => { ………………}}
-
function UPLOAD(url, method, data, files, keyName, isSecure = false) {return new Promise(){................}} - // Create formData
-
const formData = new FormData();
- // Append all received data into the form
-
// add each data in formData
for (let key in data) { formData.append(key, data[key]); } - // add each files[] if exist in the fieldName
if (files && files.length) { files.forEach(function (file, index) { formData.append(fieldName, file, file.name); }) } -
// create XMLHttpRequest so that request can be sent to the server using its instance
const xhr = new XMLHttpRequest();
-
// Keep track the ready state to be executed on some condition and return promise with resolve and reject
xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status <= 210) { resolve(xhr.response) } else { reject(xhr.response) } } } -
// Open XMLHttpRequest instance on method at some url with sync/async=false/true
xhr.open(method, `${baseUrl}${url}`, true); - // Make sure you set the request header of Content-Type and Authorization before sending the data
xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Authorization", `Bearer ${localStorage.getItem('token')}`); // using token stored in localStorage - // Finally send the formData through instance of XMLHttpRequest
xhr.send(formData);
COMPLETE CODE
function UPLOAD(url, method, data, files, fieldName, isSecure = false) {
return new Promise((resolve, reject) => {
const formData = new FormData();
// add each data in formData
for (let key in data) {
formData.append(key, data[key]);
}
if (files && files.length) {
files.forEach(function (file, index) {
formData.append(fieldName, file, file.name);
})
}
// send request to server using xml http request
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status <= 210) {
resolve(xhr.response)
} else {
reject(xhr.response)
}
}
}
xhr.setRequestHeader(“Content-Type”, “application/json”);
if(isSecure){
xhr.setRequestHeader(“Authorization”, `Bearer ${localStorage.getItem(‘token’)}`);
}
xhr.send(formData); }) }