Skip to main content

How to get upload progress in axios.

· 2 min read
Humed Essie

Introduction

Axios is promise-based node.js and browser HTTP client. It uses the native node.js http module on the server, and XMLHttpRequests on the client (browser).

info

It is isomorphic (meaning it can run in both the browser and nodejs using the same codebase).

How to get upload progress in axios?

Getting the file upload progress in any http request is a very useful feature to boost user experience.

Below is a simple example of how to get the upload progress in a browser when uploading files to any server.

Code example

import axios, {
AxiosHeaders,
Method,
AxiosProgressEvent,
AxiosRequestConfig,
} from "axios";

interface RequestTypes {
method: Method;
data?: any;
headers?: AxiosHeaders;
api: string;
handleUploadProgress: (progress: number) => void;
}
export const makeRequest = async (data: RequestTypes) => {
const config: AxiosRequestConfig = {
onUploadProgress: (event: AxiosProgressEvent) => {
console.log(
`Current progress:`,
Math.round((event.loaded * 100) / event?.total!)
);
},
method: data.method,
data: data.data,
};
const response = await axios(
` ${process.env.REACT_API_URL}/${data.api}`,
config
)
.then(({ data }) => data)
.catch((error) => {
throw new Error(error);
});

return response;
};

See Also:

Conclusion

I hope this was a helpful article. Happy coding 🎉!