Preview your uploaded image before finalizing

I am currently working on implementing a new upload feature for users of our forum. This feature will allow them to upload a personal picture. Here is what I have developed so far:

HTML

<label>Profile image</label>
    <div class="photo" id="photoPreview"></div>
    <input type="file" value="forumPhoto" onchange="return changePhoto(this);">
    

JAVASCRIPT

function showPhotoPreview() {
        var photoUrl = $.trim($("#photo").val());
        var img = $("#photoPreview img");
        if (photoUrl != "") {
            if (img.length == 0) {
                img = $("<img />").appendTo($("#photoPreview"));
            }
            img.prop("src", photoUrl);
        }
        else {
            img.remove();
        }
    }

    function changePhoto(sender) {
        var value = $(sender).val();
        sender.selectedIndex = 0;
        switch (value) {
            case "upload":
                assignPicture();
                break;
        }
        showPhotoPreview();
        return false;
    }

    function assignPicture() {
        var forumPhoto = $("#forumPhoto").val();
        if (forumPhoto == "") {
            alert("You must specify an address to use forumPhoto.");
            return;
        }
        $("#photo").val(forumPhoto);
    }
    

The current challenge I am facing is that the preview picture is not displaying properly.

JsFiddle: http://jsfiddle.net/qLsY7/

Answer №1

To achieve your goal, you will need to use either HTML5 (FileReader) or Flash. JavaScript/iFrames have security measures in place to prevent the browser from accessing and displaying local user files, thus preventing malicious activities.

For a practical example using Mootools 1.3.2, which can be converted to jQuery, I had to modify the XHR method to handle the request. Similarly, you may need to do the same with jQuery. Note that I check for FileReader capability and disable preview without it.

You can also utilize the window.FormData method to streamline the upload process via AJAX and update the image upon successful interaction with the server.

HTML:

<div id="wrapper">
    <form id="ajaxFileForm" method="post" action="processFile.php" enctype="multipart/form-data">
        <input id="imageToUpload" name="file" type="file"><br>
        <input name="somefield" type="text" value="Hello World"><br>
        <button id="previewBtn" type="button" disabled="">Preview</button>
        <button id="uploadBtn" type="submit" disabled="">Upload</button>
    </form>
    <div id="previewWrapper">
        <h4>Preview Image:</h4>
        <img style="display:none;" src="/assets/img/pixel.gif" id="preview" alt="Image Preview">
        <div id="info"></div>
    </div>
    <hr style="height:1px; border:0; background: #666;">
    <div id="responseWrapper" style="display: none">
        <h4>Response:</h4>
        <div id="output"></div>
    </div>
</div>

Javascript:

// Custom JavaScript code implementation...

Answer №2

Give it a go, if you'd be so kind.

XHTML:

<form runat="server">
    <input type="file" id="picInput">
    <img src="#" alt="picture" id="pic">
</form>

JS:

function displayImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
            $('#pic').attr('src', e.target.result);
        };

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

$('#picInput').change(function() {
    displayImage(this);
});

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

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

Sending JSON data from SpringMVC to Java server

I am working with a javascript array that is structured like this: var citizens1 = [{"startLat":null,"startLng":null,"socialSecurityNumber":null}]; The array contains 500 records, and instead of sending each record individually to the server, I convert ...

Issue encountered while attempting to pass a function within the data in React

I've encountered an issue while trying to pass a function called sectionOne and then calling it from another component. The error message I received is quite confusing. Error: Warning: Functions are not valid as a React child. This may happen if you r ...

Having trouble customizing the active state of a react router navlink using css modules in React?

Objective I am attempting to add styles to the active route in a sidebar using css modules while still maintaining the base styles by assigning 2 classes. This is the code I have tried: <NavLink to={path} className={` ${classes.nav_ ...

Executing javascript whenever a page is updated

Looking for a solution to ensure that my userscript runs every time an AJAX call modifies any page it is attached to. Is there a way to listen for XMLHttpRequests and trigger the script accordingly? ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

Can you provide me with instructions on how to change the background image?

Having trouble with the CSS code I wrote for a background-image. It's not showing up when I set it in my CSS stylesheet. I tested it and found that it only works when written in the body... <body background="Tokyo.png"> ...but not in the styl ...

If I click on a different VueJS menu, make sure to close the current menu

When using a component menu, each item is displayed independently. However, I would like the open items to close automatically when I click on another item with the menu. I employ a toggle functionality on click to control the opening and closing of the c ...

Error message: Uncaught TypeError - Unable to access property value from null reference in Quicksort.js

Can someone assist me in resolving the "uncaught typeerror cannot read property of null" issue I'm facing on line 4 of my JavaScript code? This is my first post on this platform and I hope to find some help here! function sort() { var array = docume ...

Angular: Enhance communication with controllers and directives

Currently, I am in the process of learning Angular. One interesting feature I have been working on is a directive that displays a select element. Whenever there is a change in this select element due to the ng-change event, a specific method defined in the ...

Adjust index starting from 0 in JavaScript

Struggling with setting a consistently unique index that increments by one. Here is an example of my array: const originalArr = [ { name: 'first parent array', childArray: [ { name: '1 / first child' }, ...

The Ruby on Rails application is having trouble detecting the stylesheet in the assets

I'm having some trouble displaying a border on my buttons. The button styles are defined in the app/assets/stylesheets/modules/_buttons.scss file, which I have imported into application.scss. @import "bootstrap-sprockets"; @import "bootstrap"; //m ...

Guide on redirecting to a new domain using a cookie in Express.js

I am working on a web app using Express on Node and I want to add a proxy login feature that allows users to be automatically logged in and redirected to another site after logging into my site. Within my routing function, I have the following code: res ...

The disable button functions properly upon first use, but fails to work after it has been pressed once. What steps can I

CSS $(document).ready(function() { $("#inputGroupSelect02").change(function() { var str = ""; if ($("#inputGroupSelect02 option:selected").val() == '') { $('#button').attr('di ...

Methods for concealing the "image not found" icon in Internet Explorer and Chrome through CSS

I have images displayed on a webpage. Currently, when an image is not available, both Chrome and IE display a broken image indicator. I want to hide this indicator and only show the alternative text. Is there a CSS solution to achieve this? ...

Alignment of Material-UI dialogue buttons on the left side

I have a Dialog containing three buttons as shown below: https://i.stack.imgur.com/T6o35.png Here is the JSX code: <DialogActions classes={{ root: this.props.classes.dialogActionsRoot }} > <Button classes={{ root: this.props ...

Require a more efficient strategy for iterating through lines of input

One of the challenges I'm facing with my form is that it contains 5 input lines. I need to keep any blank lines that are sandwiched between two filled lines, while removing all others. For instance, if the first line is blank, the second line contains ...

Combining multiple data sources into a single input field in VueJs

I've been exploring the idea of incorporating multiple values into a vue form input binding Here's an example snippet of my code. <template> <div> <label for=""> Employee </label> <input class="form-contro ...

Trouble fetching asynchronous data in Next.js Higher Order Component

Currently, I am in the process of creating a Higher Order Component (HOC) that will fetch user data from my API and then provide props to the wrapped component. This will allow the component to redirect the user based on their role. Although the HOC appea ...

What is the best way to access an error's body in order to retrieve additional error message details when using the forge-api with nodejs?

I'm struggling to retrieve the body content when an error is returned from the API request. I've attempted creating a bucket with uppercase letters, but all I receive is an error object with statusCode = "400" and statusMessage = "BAD REQUEST". ...