How To Upload An Image With Jquery Client Side And Add It To A Div?
So basically, as the title says, I want to have an upload button that allows a client to upload an image and it will then be displayed in a div. Of course, this would just be clien
Solution 1:
Here is a working JSFiddle for what you are looking for
functionreadURL(e) {
if (this.files && this.files[0]) {
var reader = newFileReader();
$(reader).load(function(e) { $('#blah').attr('src', e.target.result); });
reader.readAsDataURL(this.files[0]);
}
}
$("#imgInp").change(readURL);
As a side note, the above solution uses jQuery although it is not required for a working solution, Javascript only :
functionreadURL(input) {
if (input.files && input.files[0]) {
var reader = newFileReader();
reader.onload = function (e) {
document.getElementById('blah').src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
And the HTML:
<inputtype='file'id="imgInp"onchange="readURL(this);" /><imgid="blah"src="#"alt="your image" />
functionreadURL() {
// rehide the image and remove its current "src",// this way if the new image doesn't load,// then the image element is "gone" for now
$('#blah').attr('src', '').hide();
if (this.files && this.files[0]) {
var reader = newFileReader();
$(reader).load(function(e) {
$('#blah')
// first we set the attribute of "src" thus changing the image link
.attr('src', e.target.result) // this will now call the load event on the image
});
reader.readAsDataURL(this.files[0]);
}
}
// below makes use of jQuery chaining. This means the same element is returned after each method, so we don't need to call it again
$('#blah')
// here we first set a "load" event for the image that will cause it change it's height to a set variable// and make it "show" when finished loading
.load(function(e) {
// $(this) is the jQuery OBJECT of this which is the element we've called on this load method
$(this)
// note how easy adding css is, just create an object of the css you want to change or a key/value pair of STRINGS
.css('height', '200px') // or .css({ height: '200px' })// now for the next "method" in the chain, we show the image when loaded
.show(); // just that simple
})
// with the load event set, we now hide the image as it has nothing in it to start with
.hide(); // done
$("#imgInp").change(readURL);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><formid="form1"runat="server"><inputtype='file'id="imgInp" /><imgid="blah"src="#"alt="your image" /></form>
See the jsFiddle Fork made here to help explain how to make more use of jQuery to answer some of your comment questions.
Solution 2:
Refer this http://www.codeforest.net/html5-image-upload-resize-and-crop
you can use HTML5 tags like canvas for the same...and you can also use some Jquery plugins like jCrop for the same..
Post a Comment for "How To Upload An Image With Jquery Client Side And Add It To A Div?"