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

JavaScript and HTTP Post parameters: Consider using optional additional parameters

Managing a filtration function, I have an array of checkboxes and dropdowns. Users can select multiple checkboxes and dropdown values before clicking on the "Filter Now" button. Upon clicking the button, a POST request is triggered to my API, passing alon ...

Animate.css does not function properly when loaded locally

I'm currently using a Flask server to host an HTML file for testing purposes. Within the head of this HTML file, I have linked to a locally stored animate.min.css file (<link rel="stylesheet" type="text/css" href="{{ url_fo ...

Utilizing background images in conjunction with media queries

I have a div <div id="page"> </div> Containing the following css code: #page { background: url('images/white-zigzag.png') repeat-x; } @media (max-width: 600px) { #page { background: url('images/white-zi ...

How to stop Accordion from automatically collapsing when clicking on AccordionDetails in Material-UI

I am working on a React web project with two identical menus. To achieve this, I created a component for the menu and rendered it twice in the App component. For the menu design, I opted to use the Material UI Accordion. However, I encountered an issue wh ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

Unable to set up npm for node-resemble on macOS

Issue Encountered: Error installing node-resemble package due to missing README data and configure errors. npm install failed with exit status 1. ...

Does anyone else have trouble with the Smtp settings and connection on Servage.net? It's driving me crazy, I can't figure it out!

Whenever I attempt to connect to send a servage SMTP, it gives me this error message: SMTP connect() failed. I have tried using the following settings: include('res/mailer/class.phpmailer.php'); $mail->SMTPDebug = 2; include('res/mai ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

Mastering callback functions within AngularJS animations

As I delve into AngularJS animations, I am currently working on a slide-show animation: app.animation('slide-show', function () { return { setup: function (element) { }, start: function (element, done) { e ...

There was an issue converting the value {null} to the data type 'System.Int32', resulting in a 400 error

Attempting to make a POST request with some missing data is causing errors in my angular form. Here is the payload I am using: DeviceDetail{ deviceId:'332', sideId: null, deviceName:'test' } Unfortunately, I encountered a 400 bad re ...

Using Bootstrap 4, you can create nested rows that will automatically expand to fill their parent container, which in turn has been set

In my current setup, I have a div with the class "d-flex flex-column" that contains a navbar and a container. Within this container, there is another div with the class "d-flex flex-column" which then contains two rows. I am using flex-grow to make the con ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

Creating a Vue.js component that integrates a Bl.ocks.org graph

I'm a rookie in the world of D3 and I am trying to implement this cool d3 element into my Vue.js component. However, I've encountered an issue with the periodic rotation that I require not functioning properly. It seems to work initially but then ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

Utilize jQuery to extract data from a JSON object

While I have come across numerous examples of parsing JSON objects in jQuery using $.parseJSON and have grasped the concept, there are some fundamental aspects missing that are preventing me from successfully parsing the following VALID JSON: { "studen ...

Press the smiley icon and drag it into the designated input box

Is there a way to select and copy a smiley/emoji from a list and paste it into an input field? Although the Inspect Element Q (console log) shows that the emoji is being clicked, I am having trouble transferring it to the input field. Here is the HTML cod ...

What methods are available for implementing hover effects within attributes using a JavaScript object?

const customPanelStyle = { 'background-color': 'red', 'border': '1px solid green', ':hover'{ 'background': 'blue' } } class some extends React.Component{ rende ...

What is the best way to bring in a service as a singleton class using System.js?

I have a unique Singleton-Class FooService that is loaded through a special import-map. My goal is to efficiently await its loading and then utilize it in different asynchronous functions as shown below: declare global { interface Window { System: Sy ...

What is the process for integrating a personalized font into the <head> section of the ConvertTo-HTML?

I created a script to generate an HTML file containing information about the services on a computer, along with some additional styling. $a = "<style>" $a = $a + "BODY{background-color:peachpuff;}" $a = $a + "TABLE{border-width: 1px;border-style: so ...