Last active
December 28, 2015 20:59
-
-
Save w3villa/7561120 to your computer and use it in GitHub Desktop.
Upload image without submitting form, works on all browsers. Read the complete blog post at http://blog.w3villa.com/programming/upload-image-without-submitting-form-works-on-all-browsers/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Change the target of the form to the hidden iframe --> | |
<form id="avatar_form" action="/welcome/upload" method="post" enctype="multipart/form-data" target="uploader_iframe"> | |
<input id="avatar" type="file" name="avatar" size="30" /> | |
</form> | |
<!-- Hidden iframe which will interact with the server, do not forget to give both name and id values same --> | |
<iframe id="uploader_iframe" name="uploader_iframe" style="display: none;"></iframe> | |
<!-- Just added to show the preview when the image is uploaded. --> | |
<img id="preview" src="preview.png" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
$("#avatar").change(function() { | |
$("#avatar_form").submit(); // Submits the form on change event, you consider this code as the start point of your request (to show loader) | |
$("#uploader_iframe").unbind().load(function() { // This block of code will execute when the response is sent from the server. | |
result = JSON.parse($(this).contents().text()); // Content of the iframe will be the response sent from the server. Parse the response as the JSON object | |
$("#preview").attr("src", result.response.avatar_url); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WelcomeController < ApplicationController | |
def index | |
end | |
def upload | |
@user = User.create(avatar: params[:avatar]) | |
render text: { | |
meta: { | |
status: 200, | |
msg: "OK" | |
}, | |
response: { avatar_url: @user.avatar } | |
}.to_json | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment