Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed.

I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM.

To achieve this, I have been using .append() to insert an image element within the <div id="gallery">. However, I encountered difficulty in displaying file names along with the corresponding pictures due to the random order of rendering.

Fortunately, I came across a helpful post on HTML5 FileReader how to return result?, where I was able to modify the code to display images instead of base64 encoding.

$(function(){
$('#file_input').change(function(e){
    var files = $(this.files)
    $(this.files).each(function(i){
        readFile(files[i], function(e) {
            var imageSrc = e.target.result
            $('#output_field').append('<h4>'+files[i].name+'</h4><img class="preview-thumbs" id="gallery-img" src="' + imageSrc + '">');
            })
        });
    });
function readFile(file, callback){
    var reader = new FileReader();
    reader.onload = callback
    reader.readAsDataURL(file);
}
});
.preview-thumbs {display: block; padding: 10px 0px; width: 250px;}
.thumb-containers {}
#gallery>.img-container {display: inline-block; border: 3px solid #243d51; padding: 5px; width: 350px; border-radius: 20px; text-align: center;}
h4 {color: red; font-size: 20px; font-weight: bold;}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="file" id="file_input" class="foo" multiple/>
<div id="output_field" class="foo"></div>

My query is:

Is there a more efficient way to accomplish this task?

Appreciate your insights, Swift

Answer №1

I recently completed a project that addresses the same issues.

In my implementation, I handle file uploads in a separate class that includes Drag / Drop functionality. Essentially, you need to retrieve target.result on the "load" event.

const fileReader = new FileReader();
fileReader.addEventListener("load", this.fileReader_load.bind(this, file.name), false);
fileReader.readAsDataURL(file);


fileReader_load(fileName, event) {
    event.target.removeEventListener("load", this.fileReader_load);
    this.onFileLoaded(fileName, event.target.result);
}  

For the full image loader, visit: https://github.com/PopovMP/image-holder/blob/master/public/js/file-dropper.js

Creating an image preview is straightforward. Simply create an image element and set its src attribute to the imageData.

Access the complete source code here: https://github.com/PopovMP/image-holder

Answer №2

$(function(){
    $('#file_input').change(function(e){
        var files = $(this.files)
        $(files).each(function(i, file){
        readFile(file, function(e) {
            var imageSrc = e.target.result
            $('#output_field').append('<div class=""img-container"> <h4>'+file.name+'</h4><img class="preview-thumbs" id="gallery-img" src="' + imageSrc + '"/></span>');
        })
    });
});
    function loadFile(file, callback){
    var reader = new FileReader();
    reader.onload = callback
    reader.readAsDataURL(file);
    }
});

In response to suggestions made in the comments, I have updated the jQuery code to address issues related to duplication. If you would like to provide this as an answer, I will gladly accept it :)

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

In React Native, changing the translation of an element causes it to shift below all other elements, regardless of

Check out this sandbox project: I'm trying to create a simple animation using translation in React Native, but I'm facing an issue where when I move the element to the right and down, it goes under other elements. However, if I move it left and ...

Having trouble with updating AngularJS?

I am facing an issue while updating the guitar object in my AngularJS application. The operation is performed using the updateGuitar controller with ngMock backend. After updating the guitar object, the put request is processed by the carService. However, ...

Avoiding the unnecessary re-rendering of input fields in React when their values change

I am developing a form that is dynamically generated using JSON data fetched from an API. The JSON structure includes information about the input elements to be rendered, such as name, type, placeholder, validation rules, and more. { name: { elemen ...

Variations in the module pattern in JavaScript

Can someone help me understand the differences in these methods of creating a javascript "module"? I'm just looking for some clarification. A) var foo = function() { var bar = function() { console.log('test'); }; retur ...

What are the negative effects of placing an external CSS stylesheet link outside of the <head>

At the outset, it is well-known that the <link> tag used to connect an external CSS style sheet should ideally be placed within the <head> section of an HTML document. It is considered unconventional to place it elsewhere. However, due to my u ...

How to align items at the center in material-ui styling

I have a row of cards inside a container that I want to align in the center with equal spacing around them. I am using the material-ui UI library for the layout. Despite adding the justifyContent: center property, the cards are not evenly spaced. This is ...

Some CSS styles are not displaying correctly within an iframe

Let me start by clarifying that I am not looking to add extra CSS to the contents of an iframe from the parent document. My issue lies with a document that normally displays correctly but experiences styling issues when shown in an iframe. Whenever I searc ...

Retrieve the id and value attributes of a checkbox using the success callback function in jQuery AJAX

I'm currently working on a web application project using JSP, jQuery, AJAX, MySQL, and Servlet. Within my project, I have a table.jsp file structured as follows: <form id="frm_table"> Username : <input type="text" id="txt_name" name= ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

Can you transform your content like Google does?

Looking to create a help page with a layout similar to http://support.google.com/plus/?hl=en. Can anyone provide advice or an example of how to update the new content list without refreshing the page? When you click on something like "circles and streams" ...

React not displaying images with relative paths

In the past, I used to import images in React like this: import person from '../images/image1.png' And then use them in my code like this: <img src={person} alt="" /> Now, for some reason, I want to directly specify the image pa ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...

Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50. angular.forEach(result1, function (value, key) { $scope.percentage ...

Encode a MySQL query using json_encode to generate data for a multi-series flot chart

I'm attempting to convert a MySQL query into the specified JSON format for a flot chart, as outlined in the documentation: [ { label: "Foo", data: [ [10, 1], [17, -14], [30, 5] ] }, { label: "Bar", data: [ [11, 13], [19, 11], [30, -7] ] } ] Here i ...

Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to mainta ...

Show information in a React Native element | Firebase

Just starting out with react native and struggling to display data in a component? You're not alone! I'm having trouble too and would love some guidance on how to destructure the data for display. Any tips? import React,{useState,useEffect} from ...

Tips on altering the quantity of columns in a ul list dynamically

I'm trying to create a list with 2 columns, and I want it to switch to 3 columns when the browser window is wide enough (for example, on a 23 inch monitor). Can this be achieved using CSS or any other method? Here is my current CSS: .search-results ...

Issue with implementing styles on Navbar React component

I'm currently learning Next.js, specifically working with version 10.0.3. In my project, I am using react-bootstrap version 1.4.0 and classnames version 2.2.6. Within my project, I have a component called Navbar that I am trying to style in a certain ...

A guide on accessing header response information in Vue.js

Currently, I am operating on my localhost and have submitted a form to a remote URL. The process unfolds in the following sequence: Submission of a form from localhost Being redirected to a remote URL Sending a response back from the Remote URL to localh ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...