Upload Image Without Submitting Form, Works On All Browsers

If you will have a look at my old post on Uploading files/image with Ajax & Jquery, without submitting a form, you will find that this implementation does not works with Internet Explorer (IE). IE does not supports FormData, so either we can flash or the hidden iframe solution. Now flash is not the best solution as it is not installed in many browsers (and many of the mobile devices does not supports flash). So, the hidden iframe solution is best in our case. Here is how we can implement it :
<!-- 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" />
The above HTML code will do the job. I am using Ruby on Rails framewok. I am returning a text response (If I will sent a JSON response IE will ask to save the response). You can code the same in your languages like PHP, Java, Asp.net or any other. Here is my controller code.
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
We can write Javascript to show the preview of the uploaded image. What I have done might now be the best solution, but it works.
$(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); 
    });
  });
});
Hope this reference will serve your purpose. Let me know in case of any doubts.

(0) Comments