hibiken / stories

Medium clone built with Ruby on Rails
https://my-medium-clone.herokuapp.com/
MIT License
826 stars 270 forks source link

Image Upload #31

Open blueiconingenieria opened 8 years ago

blueiconingenieria commented 8 years ago

Hi Ken!, how you do it, when upload the profile image, the view is automatically updated without having to click on the submit button ?, you have a tutorial that explains this ?, you could help me with the js code?

Thank!

AjayBarot commented 7 years ago

@blueiconingenieria : Open this view views/users/edit.html.erb see this code.

<label class="change-avatar" id="change-avatar" style="background-image: url('<%= @user.avatar.url %>')">
  <%= f.file_field :avatar %>
  <%= icon('camera') %>
</label>

This will generate html for file upload Note: Don't forget to add html: { multipart: true } in form.

Now see this code at edit_profile.js

$("#user_avatar").change(function(){
   ProfileEdit.readURL(this);
});

after selection of image by user from the image selection window this change event of jquery will execute. and manipulate $('#change-avatar') style via help of jquery.

After the form submit rails controller will receive this kind of parameter of file.

"user"=>{"description"=>"", "location"=>"", "avatar"=>#<ActionDispatch::Http::UploadedFile:0x007fa419a1cda8 @tempfile=#<Tempfile:/var/folders/y_/32g4l1rs20g9tnm8pllbysf00000gn/T/RackMultipart20170323-2144-1xz74o4.svg>, @original_filename="stories-logo.svg", @content_type="image/svg+xml", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"stories-logo.svg\"\r\nContent-Type: image/svg+xml\r\n">}

and thus user profile image will saved in database. and user's profile pic will not saved automatically unless you clicked save change button.

Let me know If you still have a question or doubt into this functionality.