What is the method for showcasing an image before it has been uploaded?

I must start by apologizing for my English, as I am not the most fluent speaker.

Here's where I'm facing a dilemma:

I have created an application that allows users to edit questions for a game. These questions are stored on a server and can be downloaded for offline editing. Once editing is complete, the modified question is uploaded back onto the server. These questions also include images. To address this, I created a simple form that saves the image as a FormData object into another Object.

Let me walk you through how I accomplish this:

var formDataTemp = new FormData();
var qcid = // unique Id

if($('#editImageFileInput')[0].files[0] != undefined) {
    formDataTemp.append("img", $('#editImageFileInput')[0].files[0]);

    questionImageCache.push({
        qcid: qcid, img: formDataTemp
    });
}

I've omitted some of the additional data in the object for clarity.

There's also a list containing all the questions the user has previously downloaded, allowing them to navigate between different questions.

Now, I'd like to display the saved image when the specific question is revisited. Is there a way to achieve this without having to re-upload the image? Can the image be displayed directly from the JavaScript object?

Answer №1

If you're wondering how to show an image before it's uploaded in your code, here's a helpful tip using the FileReader.

Check out this Javascript snippet:

function loadImg(input) {
    if (!input.files || !input.files.length) return null;

    var fReader = new FileReader();
    var img = $('#placeholder');

    fReader.onload = function(e) {
        $(img).attr('src', e.target.result);

    };

    fReader.readAsDataURL(input.files[0]);
}

And below is the HTML code:

 <input type='file' onchange="loadImg(this);" />
 <img id="placeholder" src="#" alt="your image" />

For an example, check out this JSFiddle link.

You can adapt this idea to suit your own project needs. Happy coding! :)

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 ejs-locals in Express.js to insert script tag with data

Using ejs-locals for express 3.x (https://github.com/RandomEtc/ejs-locals) How can I add a script tag with dynamic data in a template? In my layout.ejs file, I currently have: <%- block.scripts %> In my page template login.ejs, I want to replace ...

Exploring the possibilities with New Relic and React

I am working with a react-router layout which currently contains a string that includes the New Relic javascript snippet. Now, I want to utilize the Browser Agent and set a custom attribute. newrelic.setCustomAttribute(name, value) The global variable n ...

What is the reason behind Istanbul's code coverage reporting a switch statement as uncovered even though all conditional paths are covered?

Within my node.js application, there is a class that includes a getter method with a significant switch statement. Rather than the simple example provided below, this switch statement contains numerous unreleased product-specific values replacing 'a&a ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

Updating the value of a rails parameter with JavaScript

I am trying to enhance my search form by pre-populating the fields with the "last searched values" when a user submits a search. The search form and results are displayed on the same page, and if there is no previous search, the fields should show placehol ...

VS code is showing the directory listing instead of serving the HTML file

Recently, I attempted to use nodejs to serve the Disp.html file by following a code snippet from a tutorial I found on YouTube. const http = require("http"); const fs = require("fs"); const fileContent = fs.readFileSync("Disp.html& ...

Is it recommended to use async callback as a best practice?

Until now, I have always called async callbacks without returning them. Unfortunately, I recently discovered that the code following the callback call also gets executed. What a realization! Let me illustrate with an example: var asyncFunctionNoReturn = ...

Getting the entire data block in ReactJS: A step-by-step guide

I have encountered an issue with a component I created that only displays the value of block[0], rather than showing the entire block value. For instance, if I input: HI Stackoverflow It only shows "HI" and not the complete content of the field. Is th ...

The reason behind Node.js using 7 threads per process

Upon starting a Node.js process, the top command displays 7 threads connected to the process. What exactly are these threads responsible for? Furthermore, as the workload on the API rises and request handlers start asynchronously waiting for other upstre ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

What could be causing the Fontawsome icon to malfunction within a Bootstrap table item?

I am currently utilizing Fontawsome free version 5.15.4, along with Bootstrap 5.1 to develop a table using JavaScript. let newBtn = createAnyElement("button", { class: "btn btn-success", onclick: "createUser(this)&q ...

Why is the table not sorting when I apply filters?

I am encountering an issue where the data filters and table sorting are not working together. When I apply filters, the sorting functionality stops working. The filters work fine independently, but once applied, they interfere with the sorting feature. Any ...

Error in clientWidth measurement providing inaccurate width

I recently adjusted the width of an image (img tag) to be 1150px * { margin: 0; padding: 0; box-sizing: border-box; user-select: none; } #background-image-myos { border: 2px solid black; border-radius: 5px; width: 1150px; } Sur ...

What is the best way to assess each item in an array and apply the useState() hook based on a specific condition

I am currently working on a simulation for a blackjack hand and have run into an issue with my code. The game follows these steps: users receive two random cards and a total point value, then click 'hit' to draw another random card from the deck. ...

Track the cursor's movement

Looking to add an animation effect to my website. I want the navbar to follow the cursor within a limited space when hovered over. Check out this example for reference: . Here's the code I have so far, but it's not quite achieving the desired res ...

Can Three.js be used to create a compact canvas?

I've successfully implemented a three.js scene on my website where users can drag to rotate an object. However, I don't want the scene to take up the entire webpage. I tried adjusting the field parameters with the following code: renderer.setSiz ...

Implement a dynamic table in real-time with jQuery AJAX by fetching data from JSON or HTML files

Hey @SOF, I'm trying to add an auto-update feature to my school grades webpage using jquery and ajax to refresh the data when new information is available. I also want to create a "single view" for classes. The challenge I'm facing is getting t ...

Encountering a deployment issue on Vercel while building with NextJS

I'm facing issues while attempting to deploy my Nextjs app on Vercel: Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: (0 , react_development_.useState) is not a function or its ret ...

Delete the placeholder image from a div once live content has been inserted into it

If I have a container div that displays an image when empty, but I want to remove the image when content is dynamically added to the container, what would be the most effective way to do this with jQuery? The usual method of checking if the container' ...