Import several image files using AngularJS

I recently came across a helpful tutorial that demonstrates how to upload pictures from your local computer using AngularJS directives. As a newcomer to Angular, I followed the instructions but now I'm stuck on modifying it to display the selected images as well. Most examples I found only show the filenames.

Another method I found loads files successfully and I managed to adapt it for multiple file uploads, however, it doesn't utilize Angular.

window.onload = function() {

    var fileInput = document.getElementById('fileInput');
    var fileDisplayArea = document.getElementById('fileDisplayArea');


    fileInput.addEventListener('change', function(e) {
        var file = fileInput.files[0];
        var imageType = /image.*/;

        if (file.type.match(imageType)) {
            var reader = new FileReader();

            reader.onload = function(e) {
                fileDisplayArea.innerHTML = "";

                var img = new Image();
                img.src = reader.result;

                fileDisplayArea.appendChild(img);
            }

            reader.readAsDataURL(file); 
        } else {
            fileDisplayArea.innerHTML = "File not supported!"
        }
    });

I am looking for a better approach to achieve my goal of loading multiple files, displaying them, and ultimately uploading them as byteArray data. Any suggestions would be greatly appreciated.

Answer №1

This code snippet allows users to select multiple files and display them on a webpage. To upload the files, you can utilize FormData. You can access more information on how to use FormData by visiting this link. Additionally, there are numerous resources available online that explain in detail how to upload files using FormData; simply conduct a quick search on Google.

document.addEventListener("DOMContentLoaded", function(){
        
    //Checking for File API support
    if(window.File && window.FileList && window.FileReader)
    {
        var filesInput = document.getElementById("fileInput");
        
        filesInput.addEventListener("change", function(event){
            
            var files = event.target.files; //FileList object
            var output = document.getElementById("fileDisplayArea");
            output.innerHTML="";
            for(var i = 0; i< files.length; i++)
            {
                var file = files[i];
                
                //Filtering only image files
                if(!file.type.match('image'))
                  continue;
                
                var picReader = new FileReader();
                
                picReader.addEventListener("load",function(event){
                    
                    var picFile = event.target;
                    
                    var div = document.createElement("div");
                    
                    div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                            "title='" + picFile.name + "'/>";
                    
                    output.insertBefore(div,null);            
                
                });
                
                 //Reading the image
                picReader.readAsDataURL(file);
            }                               
           
        });
    }
    else
    {
        console.log("Your browser does not support File API");
    }
}
    
html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
  background: #333;
}

#page-wrapper {
  width: 600px;
  background: #FFF;
  padding: 1em;
  margin: 1em auto;
  min-height: 300px;
  border-top: 5px solid #69c773;
  box-shadow: 0 2px 10px rgba(0,0,0,0.8);
}

h1 {
margin-top: 0;
}

img {
  max-width: 100%;
}

#fileDisplayArea {
  margin-top: 2em;
  width: 100%;
  overflow-x: auto;
}
<div id="page-wrapper">

<h1>Image File Reader</h1>
<div>
Select an image file: 
<input type="file" id="fileInput" multiple>
</div>
<div id="fileDisplayArea"></div>

</div>

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

What is the best way to set the page title on a server-rendered component when using the Next.js app router?

When loading a blog post from the server, I have access to details like the title of the post. However, based on the app router migration guide, this information is located outside my page. How can I update it? For more information, refer to the documenta ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

Opening a new window with Node-Webkit's start function

My application built on node-webkit has a control window and a separate presentation window. The control window collects data and triggers the opening of the presentation window using the window.open function. Once the presentation window is open, it can ...

Executing a file upload using ng-click="upload('files')" within Selenium Webdriver

Is it possible to automate a file upload when the HTML code does not include an < input type='file' > instead, uses a link <a ng-click="upload('files')"> File Upload </a> Clicking this link opens a file selector f ...

Initialization of Angular provider $get is missing

Within my 'app.js' file, I have the following code that is used in my config to set up $navigationProvider.doSomething(). When running this code, Test1 and Test3 are alerted correctly, but I'm having trouble with getting my this.$get method ...

Sharing objects between parallel states in Angular

Is there a way to seamlessly transfer a selected user from the details view to an edit view for parallel editing? In the details view, I capture 'selectedUser' and then need to make edits in specific fields within the edit view. There are two p ...

How can you selectively export a single function from a JavaScript file?

Within my project, I have two separate modules - one written in ts and the other in js. There is a utility within the js module that needs to be accessed by the ts module. The utility service.js looks like this: module.exports = { helloFriends: functi ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

Concealing Content within an Accordion

Looking for some guidance on setting up a mobile version of my product image with hover features. Currently using tooltips on desktop and planning to use a modified accordion on mobile, but struggling to make progress. Customized some JS to toggle an acco ...

issues arise post-transpilation with creating errors

In order to practice, I decided to create a basic TypeScript project. If it could be helpful, here is my ts.config: { "compilerOptions": { "target": "es2016", "module": "commonjs", "outDir": "./dist", "esModuleInterop": true, "forceC ...

Vue. A variable that changes dynamically in v-if conditions

How can I include a variable in a v-if statement based on my specific situation? I have a data variable called language = 'en' and a large json object with data in multiple languages (referred to as message). Here is an example of the structure o ...

Trouble with disabling default actions and transferring text

When the user clicks on loginAccount, the intention is to extract the text from the element with the id input-1 and assign it to username. This same process should occur for password, followed by form submission. However, despite using e.preventDefault() ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Is there a way to ensure one request completes before allowing another to be executed in Express/Node?

I am currently working on a task that involves fetching data from a third-party API (iTunes) to search for content provided by the API. The backend, which is handled by Express and Node, will interact with this third-party API. My goal is to trigger a POST ...

Can you explain the functionality of sinon's stub.yields method?

The explanation given in the documentation for sinon regarding stub.yields is as follows: By using stub.yields([arg1, arg2, ...]), you are essentially performing a function similar to callsArg. This will result in the stub executing the first callback it ...

Is there a way to initiate LiveServer or npm run dev/start over my local network?

Is it possible to access my project (npm run dev/liveServer) over my home internet network so that my iPad, phone, or iMac could also view the project live as it's being developed (all connected to the same wireless network) without the need to deploy ...

Manage the number of choices available on a drop-down selection form

I am working with a PHP variable $a of an integer type. Based on the value assigned to $a, I want certain options to be visible in a form. For example, if $a=1; then only the first two options should be displayed, and if $a=2; then the first three option ...

Are there any Angular-specific content sliders similar to jQuery's bxSlider available?

Looking to incorporate a content slider similar to jQuery bxslider, but prefer one that is not reliant on the jQuery library. I have yet to include jQuery externally in my Angular app. Are there any bower components available for a content slider that do ...

Guide on how to compare two arrays in JavaScript and identify mismatches by their respective indices

let x=["e","f","g","h"]; let y=["f","e","g","h"]; I want the following result: Inconsistent array from x Inconsistency array=["e", "f"]; ...

How to effectively trigger a function to load images in React

When my react app loads, I want the images to load immediately. This involves calling the function collectionChanged(e.target.value) on application start. Inside a .jsx file, there is a function named getHomePage() which contains 4 functions. Upon calling ...