Obtaining numerous files in base64 along with their respective file names using FileReaderAPI in Javascript

When I upload 3 items named png1, png2, and png3, the result will be as follows:

alert 1

png1 / base64 string conversion

alert 2

png2 / base64 string conversion

alert 3

png3 / base64 string conversion

I experimented with this code snippet.

    function readFile() {
        var input = document.getElementById('gallery-photo-add');
        var nameOfFile = "";
        for (var i = 0; i < input.files.length; ++i) {
            nameOfFile = input.files.item(i).name;
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.addEventListener("load", function (e) {
                    alert(nameOfFile);
                    alert(e.target.result);
                });
                reader.readAsDataURL(this.files[0]);
            }
        }
    }
    document.getElementById("gallery-photo-add").addEventListener("change", readFile);
<input type="file" multiple id="gallery-photo-add" style="overflow: auto;">

Answer №1

Combine the filename and base64 using the + operator in a single alert.

For more information on JavaScript operators, you can check out this reference.

Note: Alerting the filename and base64 together is not straightforward as base64 comes from the FileReader API while the filename is from the input element.

I have encapsulated the base64 and alert logic within a function and simplified the JavaScript code for you to call the function using onchange.

View the working demo here: https://jsfiddle.net/usmanmunir/hpej8f6o/

Run the snippet below to see it in action.

function readFile(input) {
  //Store file name
  var filesName = []
  //Get total files
  var filesTotal = input.files.length;
  for (var i = 0; i < filesTotal; ++i) {
    //Store file names
    filesName.push(input.files.item(i).name)
    var reader = new FileReader();
    //Display alert and base64
    function displayAlert(i) {
      reader.addEventListener("load", function(e) {
        alert(filesName[i] + ' Base64 ' + e.target.result);
      })
    }
    reader.readAsDataURL(input.files[i]);
    //Display Alerts
    displayAlert(i)
  }
}
<input type="file" multiple id="gallery-photo-add" onchange="readFile(this)" style="overflow: auto;">

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

Using ES6's object destructuring to set default values for nested parameters

Utilizing es6 object destructuring for supplying default parameters to a function. function mapStateToProps({ shops: { cakeShop: {}, pieShop: {} }) { return { CakeShopName: shops.cakeShop.Name, PieShopName: shops.pieShop.Name } } An issue ari ...

The responses for several HTTP POST requests are not being received as expected

I am facing a challenge in retrieving a large number of HTTP POST requests' responses from the Database. When I try to fetch hundreds or even thousands of responses, I encounter issues with missing responses. However, when I test this process with onl ...

The Heroku app seems to be malfunctioning (Issue with deployment?)

After deploying my application that utilizes JavaScript, Express, and Node.js on Heroku, I encountered an issue where the functionality of the app is not working at all when accessed through Heroku. Interestingly, everything works perfectly fine when teste ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

Issues with anchor tag click event in Firefox browser not functioning as expected

I have encountered an issue while trying to create an anchor tag in a TypeScript file. When clicking on this button, the anchor tag should be created. This functionality is working correctly in Chrome and IE, however, it seems to be not working in Firefo ...

No response received from the server

I recently encountered an issue with an ajax call that updates my database. While the call successfully goes out and updates the database, I do not receive any response back from the server. I have confirmed this using firebug, noticing that there is a po ...

Create a new one-dimensional array by stacking the columns of a matrix

In my current project, I am dealing with a complex array of arrays where each inner array contains objects. My goal is to transform this multidimensional array into a flat array organized in a column-wise order. Here is the code snippet that I have implem ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Tips for generating an HTML template as a string using jQuery

I have developed a dynamic modal using plain JavaScript, triggered by a button click. This modal is controlled based on the attributes `data-open-hours` and `data-closed-hours` in the HTML. If you take a look at my demo, you will notice an issue. Let me e ...

The NodeJS and Python-Shell .run function fails to display the standard output

I am currently working with NodeJS and a Python script. To retrieve results from my Python script, I have been using Python-Shell which you can find detailed documentation for at: github.com/extrabacon/python-shell Typically, to get prints from the scrip ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

Manipulating SQL database tables using PHP

After struggling for about 5 hours, I'm still unable to make this code work. Despite my best efforts, the unique nature of my codes seems to be a challenge. I am attempting to update entries in a specific table within my SQL database named userdb. The ...

Fullcalendar time correction with Ajax and Flask: Step-by-step guide

After creating an appointment on the calendar, the start and end time display correctly. However, upon reloading the page, the datetime appears different on both the calendar and in the database. For instance, if I schedule an appointment from 09:00 AM to ...

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

Issues with websockets functionality have been reported specifically in Firefox when trying to connect to multiple

I am currently working on a websocket client-server application. The client code is as follows: const HOST = "wss://localhost:8000"; const SUB_PROTOCOL= "sub-protocol"; var websocket = new WebSocket(HOST, SUB_PROTOCOL); websocket.onopen = function(ev ...

The dataset controller in Chart.js returns 'null' when the chart is rendered

Greetings, I must preface this by saying that I am not well-versed in javascript/web development and do not claim to have a strong understanding of the language or its environment. My expertise lies in embedded C/C++ programming, and my foray into learning ...

Efficiently loading and locally filtering data in Angular 2 using Observables

In my Angular 2 application, I have successfully implemented an input with autocomplete that calls an API for server-side filtering and value retrieval. However, I am now facing a challenge as I need to add more inputs to my page that do not require server ...

Events are not being triggered when using node busboy with express 4 and ng-file-upload

I am currently utilizing the mean.io stack along with ng-file-upload module. Does anyone have any insights as to why the events are not being triggered? Your assistance would be greatly appreciated. Client controller('ArticleParentCtrl', [&apo ...

I am looking to have my page refresh just one time

I have created an admin page where I can delete users, but each time I delete a user, the page requires a refresh. I attempted to use header refresh, but this action caused my page to refresh multiple times. Is there a way to ensure that my page only refr ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...