Send the image by attaching it and encoding it in base64 before sending it as JSON

Looking for a way to encode and send images via JSON using base64, but struggling with getting the result from the FileReader object. Any assistance would be highly appreciated.

<form>
    <label>Picture
         <input type="file" accept=".jpg, .jpeg, .png" name="picture" required>
    </label>
</form>
async function push() {
// additional actions here
    let form = new FormData(document.querySelector('form'));
    let json = construct_json(form);
//calls  of other functions
}

function getBase64(file) {
   let reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () { // suspected issue here
     reader.result;
   };
}

function construct_json(form) {
    let json = {
        picture: getBase64(form.get('picture')),
    };

    return JSON.stringify(json);
}

UPDATE: Encountering the same problem when trying to use JSON in the push() function, even adding await does not solve it. Suggestions on how to display JSON in the push() function would be greatly welcomed.

Answer №1

A common error occurs when the reader.onload method is called in your code. You can refer to this resource for an example.

Don't forget to include addEventListener and a callback function when the upload process is completed. Here is the code snippet that needs to be added:

window.addEventListener("change", push);

function getBase64(file, callback) {
  let reader = new FileReader();
  reader.onload = function(e) {
    // console.log(e.target);
    // It seems like there might be an error here

    callback(e.target.result);
  };
  reader.onloadend = function(e) {
    return e.target.result;
  };
  return reader.readAsDataURL(file);
}

async function construct_json(form) {
  await getBase64(form.get("picture"), data => {
    let json = {
      picture: data
    };

    return JSON.stringify(json);
  });
}

Answer №2

After considering the comment, it is recommended to check out the example on sandbox

To avoid getting stuck in callback hell, it's best to create a promise. In this case, a promise for the base46 Function has been implemented. Check out Promisification

const getBase64Promise = function (file) {
  return new Promise((resolve, reject) => {
    getBase64(file, (success,err) => {
        if(err) reject(err)
        else resolve(success);
    });
  });
};

Consider implementing your code in a similar manner:

async function construct_json(form, callback) {
  let data = await getBase64Promise(form.get("picture"));
    let json = {
      picture: data
    };
    return json;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a fetch request is called inside a map function in React, the return

I attempted to retrieve a map array through fetch resolves so that each element inside favoriteCards would return a value and assign it to the test variable useEffect(() => { const test = favoriteCards.map((card) => { accuWeatherApi.getCurrentW ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

Adjust the DIV shape to fit perfectly within the browser window without overlapping with any other elements

http://jsbin.com/iGIToRuV/1/edit Currently, I am working on developing a WYSIWYG website designer as part of an experimental project for various purposes. The ultimate goal is to ensure that it is both desktop and mobile-friendly. However, I have encount ...

How does the Express server collaborate with Webpack middlewares to facilitate live reloading?

As I delve into node, express, and webpack, I find myself grappling with the concept of middleware. Upon examining the code snippet below, my current understanding is that once the web server is up and running and I navigate to http://localhost:7770/, the ...

Tips for hiding multiple markers when zooming out

Is there a way to prevent the same marker from appearing multiple times? latlngbounds.extend(markers[i].getPosition()); map.setCenter(latlngbounds); map.fitBounds(latlngbounds); ...

Encountered a Metro Bundler issue while trying to install a custom npm package

Ever since I developed this npm package and installed it in a different application, I keep encountering the following error during runtime: An internal error has been encountered by Metro Bundler Surprisingly, this issue occurs even if the project is br ...

The functionality of submitting an Ajax form is only successful on Firefox browser

My Ajax login form is functioning properly only on Firefox. However, in other browsers, it continues to submit the form and load the function page. I aim for it to send the two fields to a function page, validate them in the background, and display the res ...

The canvas is giving Three.js trouble when it comes to rendering

I included the script in my index.html file, but when I view the page, it displays as rendered without any content inside. I'm unable to locate the issue. Below is the code from the external .js file: var wdt = $('.design').width(); va ...

Real-time updates for UI data in Next.js Firestore are not being reflected

I'm currently working on implementing real-time changes using nextjs and Firebase Firestore. However, I've noticed that I still need to refresh the page in order for the updates to be visible. const [getUsers, setUsers] = useState(""); const che ...

Lazy loading for natives not functioning, despite flags being turned on

I recently attempted to update my website by adding the new loading="lazy" attribute, following the example shown at: https://web.dev/native-lazy-loading While everything seemed to be working fine as demonstrated in the video, when I checked the waterfall ...

Adding HOST with the sails-mongo adapter: Best practices for seamless integration

I have successfully installed sails-mongo via npm and am currently running a basic sails.js application. However, my host is not being recognized. My MongoDB is operational on the default port 27017. Whenever I generate a model, I encounter an error while ...

What is the best way to represent the amount of water consumed from milliliters in a visual

I need assistance in displaying the calculated amount of cups using cup icons. Keep in mind that one icon represents 220 ml. My objective is to reach 3.60 liters of water intake. This equates to approximately 16.36 cups. Is there anyone who can assist me ...

Troubleshooting: React-native iOS images not displaying due to pods problem

While setting up a new package in my react-native application (specifically createMaterialTopTabNavigator from react-navigation), everything seemed to be going well. However, after the installation was complete, an error occurred (@react-navigation/materia ...

What is the best way to utilize the features of component A within component B when they exist as separate entities

Component A has all the necessary functionalities, and I want to use it in Component B. The code for ComponentA.ts is extensive, but it's not written in a service. How can I utilize the logic from Component A without using a service, considering both ...

Activate or deactivate a text box within a table based on the checkbox's status

I am seeking assistance with jQuery to enable or disable a textbox within a table when a checkbox is checked. Below is the code snippet from my edit.cshtml file. <table id="scDetails" class="dataTable"> <thead> & ...

What steps can be taken to prevent interference between my nested functions?

My function checks the values of radio buttons and dropdowns against their data values, displaying "Correct!" if they match and "Incorrect" if they don't. When testing, if I comment out either the radio button portion or the dropdown portion, the oth ...

Secure your data transfer by encoding passwords with JavaScript before sending them to PHP for decryption, a reliable

For my website, I have decided to use Google Checkout and Paypal as payment methods. Instead of installing SSL certificates for my site, which can be expensive and complex, I will redirect users to the secure Google/Paypal sites for processing payments. A ...

Toggle class on element based on presence of class on another element

If I have 4 boxes and the user is required to choose one. I aim to assign an active class to the box that the user clicks on. However, if the user selects another box, I want to remove the class from the first clicked box and apply it to the newly clicked ...

Using JavaScript to set the value of an input field based on the selected option value

I'm attempting to display the value of the selected OPTION in a separate INPUT FIELD, but for some reason it's not working and I can't figure out what's causing the issue. Here’s the code snippet: <!doctype html> <html lan ...

ReactAppI am facing an issue where the browser fails to refresh the page upon saving changes in my JavaScript file using the VS code editor

Can anyone remind me of the tool we can install to refresh the browser page automatically whenever we save changes in our editor? ...