ndesign11
ndesign11

Reputation: 1779

Using jquery with file upload form field

I'm not sure this is possible without some kind of server interaction but I am hoping it is for prototyping purposes. I have a file upload form field. I would like user to be able to select image from hard drive and jquery will put that image into a div in the DOM.

Here is my code

<div class="label">Upload Your Own Logo</div>
  <input name="upload" type="file" id="logo-upload">

Div where image should go

<div class="user-logo">logo.png</div>

Upvotes: 0

Views: 410

Answers (2)

Jahnold
Jahnold

Reputation: 7683

If the user's browser has HTML5 FileReader API then this is possible:

var file = document.getElementById('logo-upload').files[0],
    reader = new FileReader();
reader.readAsDataURL(file);

reader.onloadend = function(e) {
    var image = $('<img>').attr('src',e.target.result);
    $(image).appendTo.('.user-logo');
}

Upvotes: 1

srijan
srijan

Reputation: 1512

You don't need AJAX for that. In fact you don't even need jquery.

<input type="file" name="ss" id="fileUpload" onchange="dothis()"/>
<div id="picDiv"></div>

use function dothis() to append the image you upload inside #picDiv

function dothis()
{
    var oImg=document.createElement("img");
    oImg.setAttribute('src', document.getElementById("fileUpload").value);
    oImg.setAttribute('alt', 'na');
    document.getElementById("picDiv").appendChild(oImg);
}

Don't forget to check if the file is valid image or not, which I leave it upto you.

Upvotes: 0

Related Questions