Suggestions to upload image using jQuery ajax
I have a form that has 3 inputs:
[1] text input field for a status update
[2] file upload (for a picture)
[3] text input field for attaching a link
The user toggles between each one depending on what they want to do. For example when choosing [2], inputs [1] and [3] are hidden.
All of these inputs are c开发者_运维知识库ontained within a single form with id posts_form
. Options [1] and [3] post via Ajax to different controllers.
My problem now is with option [2] because it is not possible to upload images using jQuery ajax.
Some solutions I've seen involve using the jQuery Form plugin, but I wonder if it would be possible to do image uploading without the use of a plugin.
For example this would be the code base for uploading which of course doesn't work.
$.ajax({
url: 'chat/upload/' + <?php echo $page_id; ?>,
type: 'POST',
data: $('#posts_form').serialize(),
dataType: 'html',
beforeSend: function(){
$('#loading').show();
},
success: function(html) {
$('#attach').replaceWith(html);
$('#loading').hide();
$('#posts_form input').val('');
$('.posts_link').val('');
$('#chat_input').hide();
}
});
Any suggestions on what could be added / changed to permit image upload using jQuery only, without plugins?
Thanks.
There is no straightforward way to upload a file via AJAX. That is a limitation in HTML4. Workarounds are using an iframe or Flash.
In HTML5, a File API is introduced to solve that problem. Here's a demo of leveraging that API (using a Firefox 3.6+), which allows you to drag and drop an image and load it without sending it back to the server: http://html5demos.com/file-api. It also supports multiple files: http://demos.hacks.mozilla.org/openweb/DnD/.
You can read about that specification on W3.org, if you are keen.
If you cannot depend on clients to have browsers supporting HTML5's File API, you may either roll you own or choose to use a library that implements the iframe workaround:
- http://www.fyneworks.com/jquery/multiple-file-upload/
- http://jquery.malsup.com/form/
- http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
- http://aspzone.com/tech/jquery-file-upload-in-asp-net-mvc-without-using-flash/
Your best choice is this plugin. You're wasting your time trying to do it without this.
http://jquery.malsup.com/form/
精彩评论