How to upload and preview the uploaded image using AJAX
I have created the following web page:
...
<img alt="" src="images/frame.png" id="contact-image" />
<form enctype="multipart/form-data" action="PHPScripts/upload.php" method="POST">
<input type="file" id="browseContactImageButton" name="image"
accept="image/jpg,image/jpeg,image/png,image/gif"
onchange="this.form.submit();" />
</form>
...
I want to be able to upload the the image to file system or database (haven't decided yet) and to be able to see the uploaded image in the <img id="contact-image" /开发者_如何学JAVA>
immediately after the file has been uploaded, without reloading the page, i.e. using AJAX.
Can you show me the concept that I should follow? I know that I am making a mistake by calling the PHPScripts/upload.php
on form submitting. My guess is that I should call some javascript function instead, but where do I go from there and what should that function look like? Thanks.
With MVC or any other backend it's fairly simple. Let's assume you have a controller with the name UploadPicture. When the webserver has finished uploading the picture, you would simply make the server return json with the image path or whatever you need.
I would recommend using jQuery since it's an excellent framework to work with Javascript and has a good cross-browser support.
I've done this before and it was just like what I described above.
IF you happen to know the path and image name, then you wouldn't even need to return anything from the server. You would simply do with jQuery when the upload has finished:
$("#contact-image img").attr('src', 'http://PathToImage');
And you could use $.ajax to trigger when the submit has finished.
Reference on $.ajax - http://api.jquery.com/jQuery.post/
I hope this helps.
Try the Ajax upload
You can find explanations and examples it here:
http://www.zurb.com/playground/ajax_upload
have you tried swfupload?
here is a demo that uses php
I will suggest you to use the YUI file upload or JQuery plug in for file upload. Once the file is upload you can retrieve the file path from the server and update using the JS on the client side.
var imgControl = document.getElementById('image');
imgControl.src = filePathFromServer;
And if you want to try something new HTML5 ... i will suggest to have a look at this demo.
Here's the best solution in my opinion. It doesn't involve jQuery and it provides AJAX-like functionality. Thank you to everyone who has put an effort in helping me resolve this. Cheers!
http://www.articlealley.com/article_573896_81.html
精彩评论