Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 8, 2022 07:11 am GMT

The Better Way of Sending Data to the Backend

If you are a front-end developer, who ever worked on picture uploading, video uploading or audio uploading to the backend, then you should know that uploaind these types of data is a slow process, and it even becomes laggy when a large data is being upload at once.

When we want to upload a picture or audio to the backend, we can't just send it to the backend in their original format. Every picture or audio, has a binary format, which is first being converted to base64 format in the frontend, which is then being sent to the backend, and if you want to get the data again from the backend, then you can't show it on the frontend, in their base64 format, which means that with every GET request, the backend have to convert the data from the base64 to the binary, and then it perfomrs GET request.

You can cleary see, that it's a two time conversion. First from binary data to base64 data and then again from base64 to binary data, and eventually this process takes large data to upload slowly.

But, there's always a solution. What we have to do instead of converting it to base64 in the frontend, is sending binary data directly to the backend, which means that even backend don't have to convert it in any way, which makes the process fast.

But, now the question is that how to do that?

You can use FormData() constructor to send binary data directly to the backend.

At first, you have to create an instance of the formdata.

var formData = new FormData();

and then you have to append the data to the formData.

formData.append('username', 'Chris');

Let's take an example.

const sendAudioAsync = (audioChapter, index, audioBookId) => {    message.warning(`Uploading audio ${index}`);    const sendingAudio = new FormData();    sendingAudio.append('audio', audioChapter?.audio);     sendingAudio.append('size', audioChapter?.audio?.size);     sendingAudio.append('name', audioChapter?.audio?.name);     sendingAudio.append('title', audioChapter?.title);     sendingAudio.append('time', audioChapter?.time);    sendingAudio.append('index', index); }

The above example is the real time example of the client I am working for, in which I have to send audio and its detail to the backend, and I used FormData to send it.

FormData is always in key value pair, and you have to put a name and the data as key value pair, if using FormData to send binary data directly to the backend.


Original Link: https://dev.to/manas_dev/the-better-way-of-sending-data-to-the-backend-bdp

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To