开发者

Rails click on div to upload image

开发者 https://www.devze.com 2023-03-27 11:00 出处:网络
<div id=\"photo_attachment_container\"> <%= f.file_field :photo %> </div> Currently this is how my standard image upload button looks in rails. I would like to improve it aesthetic
    <div id="photo_attachment_container">
        <%= f.file_field :photo %>
    </div>

Currently this is how my standard image upload button looks in rails. I would like to improve it aesthetically by having a div on the page with a background image a开发者_StackOverflows placeholder, and people can click on that div to upload an image (the function currently provided by the button) and when the image is uploaded it becomes the background of the div.

Also paperclip handles the upload and can resize to the size of the div.

How can I do something like this in rails? Thanks

Rails click on div to upload image


If you want to show a browse file prompt you have to use a form file input.

What you can do is position the file input absolutely within the div and track the mouse around the div when it moves. That way, wherever the mouse clicks on the div, the file input will be under the mouse and show the browser prompt.

You can then hide the file input using opacity 0.

Obviously this method requires javascript.

You can then apply an onchange listener to the file input so that on selection of a file it submits the form to a hidden iframe. The server uploads the image in the iframe and then prints something like

window.top.returnFileUrl('new-file-name.jpg');

If this function is defined in the parent window....

function returnFileUrl(url)
{
    document.getElementById('image-div').style.background = 'url('+url+')';
}

That is untested code to point you in the right direction.

0

精彩评论

暂无评论...
验证码 换一张
取 消