我希望在上传图片时使用 :hint 以立即在表单中显示它。我刚刚发现了该功能,但由于出现错误,似乎没有正确使用它。我正在寻找替换以下内容
<div class="input-group " style="width: 100% !important;">
<span class="input-group-btn">
<span class="btn btn-small btn-primary btn-inverse" onclick="$(this).parent().find('input[type=file]').click();">Browse</span>
<%= f.file_field :avatar, onchange: "$(this).parent().parent().find('.form-control').html($(this).val().split(/[\\\\|/]/).pop());", style: "display: none;" %>
</span>
<span class="form-control"></span>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
在以下形式中,使用 :hint
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: {method: :put, multipart: true}) do |f| %>
<%= f.error_notification %>
<% if @user.avatar? %>
<%= avatar_for(@user) %>
<% else %>
<%= image_tag("Avatar_default.jpg", alt: "No profile picture", width: "100%") %>
<% end %>
<br>
<%= f.input :avatar, :as => :file, :hint => image_tag(f.object.avatar.url) %>
<%= f.input :avatar_cache, :as => :hidden %>
<%= f.button :submit, "Update", :class => "btn btn-primary" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想要一个浏览文件按钮,选择图像,然后在用户继续填写表单时查看图像中的预览。
我当然没有填写以下权利: image_tag(f.object.avatar.url)
我建议您使用 javascript/jquery 帮助来完成此操作:
function showImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#your_preview_id')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
此代码从您的输入中获取图像并将其插入#your_preview_id元素中,但是,对于 id,您需要执行以下操作:
<%= f.input :avatar, :as => :file, id: "image_upload_id" %>
<%= f.button :submit, "Update", :class => "btn btn-primary" %>
Run Code Online (Sandbox Code Playgroud)
将此 ID 提供给您的输入,为他绑定更改,然后执行以下操作:
$('#image_upload_id').on('change', function() {
showImage(this);
})
Run Code Online (Sandbox Code Playgroud)
不要忘记为您的图像预览创建一个着陆点:
<div id="your_preview_id"></div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |