16

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 client side, so if the page was ever refreshed then the image would disappear.

The image would then be styled accordingly and given fixed widths and heights.

I searched online and couldn't find anything at all.

Very new to jQuery, although I can code fluently in Javascript.

Also not to sure if this is possible or not without the help of AJAX and/or PHP. Would like to avoid these if possible.

All help is greatly appreciated.

Fizzix
  • 23,679
  • 38
  • 110
  • 176
  • 3
    Everything you say is very achievable, but don't you feel you should have made a head start yourself? – MarsOne Sep 25 '13 at 13:05
  • 1
    @MarsOne Sometimes it's hard to make a "head start" when you don't even know where the starting line is. – SpYk3HH Sep 25 '13 at 13:35
  • @SpYk3HH, That's the best line ive heard on SO? Who said that? – MarsOne Sep 25 '13 at 13:42
  • @MarsOne uhm ... me? I don't know if I heard it somewhere. It's just something I've said for years in trying to help friends and people with other real life problems. – SpYk3HH Sep 25 '13 at 13:48
  • Why is this question getting so many negs? Come on SO Community. You're being to harsh. This question is perfectly legit and already has a good answer. Why neg a question **AFTER** it has already been answered? – SpYk3HH Sep 25 '13 at 13:50
  • Hmm. Nice. Personally i prefer " What doesn't kill you only makes you stranger"-Joker – MarsOne Sep 25 '13 at 13:51
  • 1
    @SpYk3HH, I disagree with the question being legit, far from it. The OP has not produced any code to show what he/she has attempted. He has neither stated whether he tried anything. only a mention of searching online. I mean if we start encouraging these questions we are defeating the purpose of SO being "exclusive" – MarsOne Sep 25 '13 at 13:54
  • @MarsOne but it's not "exclusive". Google search almost any code problem, SO is the first thing that pops up 90% of the time. Fact is, people use this site for more than just "check my code". If you want that, there's a [stackexchange site](http://codereview.stackexchange.com/) for that. In fact there are quite a few of "exclusive" sites for that in SE. Otherwise, accept the fact that SO has "advertised" itself and has become the "Google" of "code work". Thus, not every question (even according to their own Meta FAQ's) "needs" a show of work. – SpYk3HH Sep 25 '13 at 13:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38032/discussion-between-marsone-and-spyk3hh) – MarsOne Sep 25 '13 at 14:00
  • 10
    Many "nubs" come here to learn and find some encouragement onto the right path. If we just neg them, especially after they are getting answer, they may become discouraged. Then you just knocked another "potential intellect" who could have been the "next big thing" completely out of the water all because you want something from this site that ***does not exist***. If you want an *exclusive* code site, join a forum. Other wise, enjoy the ***Question*** and ***Answer*** site that is here – SpYk3HH Sep 25 '13 at 14:00
  • Given the accepted answer, "upload" is not really the right word for loading the image into the page, rather than uploading it to a server. Perhaps that's what you meant by "client side"? I think just "loading" rather than "uploading" could be a better question title. The accepted A does not use the mentioned PHP or Ajax, more typical methods of truly uploading to a server, FTP space, or S3 or something like that. This readAsDataURL is great if you don't need to actually upload the image to the web and can use it on page / locally to suit your needs, but isn't uploading anything. Right? – OG Sean Jul 08 '18 at 19:55

2 Answers2

32

Here is a working JSFiddle for what you are looking for

function readURL(e) {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        $(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 :

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

        reader.onload = function (e) {
            document.getElementById('blah').src =  e.target.result;
        }

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

And the HTML:

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

function readURL() {
 // 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 = new FileReader();
  $(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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" runat="server">
        <input type='file' id="imgInp" />
        <img id="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.

Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
Nunners
  • 3,047
  • 13
  • 17
  • 1
    Dang you! That's exactly what I was putting together! LoL – SpYk3HH Sep 25 '13 at 13:08
  • Wow, works great! Thanks for your help! And unluck SpYk3HH, but theres an upvote for you anyways haha. – Fizzix Sep 25 '13 at 13:10
  • 1
    BTW, you can easily shorten that by making `readURL` the function of the change. – SpYk3HH Sep 25 '13 at 13:11
  • Not to sure how to do that haha... How would I add styling to the created image? Such as a width and height, or even easier, just a CSS class? – Fizzix Sep 25 '13 at 13:12
  • @fizzix you simply add the class to the `` tag that you are setting the src of. – Nunners Sep 25 '13 at 13:13
  • Ahh alright. I can see that now. So only the `img` tags source is changing, it isn't actually being created every time. Fantastic, thanks for your answer :) – Fizzix Sep 25 '13 at 13:15
  • Although, would it be possible to not display the `img` until an upload is made? Otherwise there will always be a broken image before the first upload. – Fizzix Sep 25 '13 at 13:18
  • Set the `display=none` on the image and once the line `reader.readAsDataURL(input.files[0]);` has run set the display to be block. i.e. `` and `$('#blah').css('display', 'block');` – Nunners Sep 25 '13 at 13:19
  • I'm not an as in depth user of jQuery @SpYk3HH :(. I often forget about the simpler jQuery methods... – Nunners Sep 25 '13 at 13:23
  • It's ok. I updated this answer to include a fork of original fiddle that contains a "fuller" jQuery layout answering all of these questions. It's also "well" commented to help explain everything that is taking place – SpYk3HH Sep 25 '13 at 13:32
  • @user1032531 True, but you can use a [polyfill](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#file-api) to replicate the functionality in Pre-IE10 browsers. Please note that these may require Flash/Silverlight to work – Nunners Jun 30 '15 at 14:13
0

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..

Neel
  • 11,625
  • 3
  • 43
  • 61