Rails 3:上传前预览图像的最佳方式 [英] Rails 3: best way to preview image before upload

查看:130
本文介绍了Rails 3:上传前预览图像的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在提交表单之前预览图片。
我使用Rails 3并且需要与浏览器兼容的东西。
任何想法如何实现?

I need to preview an image prior to submitting a form. I work with Rails 3 and needs something that is browser compatible. Any ideas how I can achieve that?

推荐答案

所以! :)主要的想法是使用FileReader Javascript类,这对你需要做的事情非常方便。

So! :) The main idea is to use the FileReader Javascript Class, which is really handy for what you need to do.

您只需要在文件输入上侦听更改事件,然后调用将使用FileReader类的readAsDataURL()方法的方法。然后你只需要用方法的返回结果来填充预览img标签的来源......

You just have to listen to the "change" event on your file input and then call a method that will use the "readAsDataURL()" method of the FileReader class. Then you just have to fill the source of a "preview img tag" with the returned result of the method...

我给你写了一个简单的jsFiddle ,实现了你想要的。你可以在下面看到我的代码:

I've wrote you a simple jsFiddle that achieves what you want. You can see my code below:

<!-- HTML Code -->
<div class="upload-preview">
    <img />
</div>
<input class="file" name="logo" type="file">    



//JS File
$(document).ready(function(){
    var preview = $(".upload-preview img");

    $(".file").change(function(event){
       var input = $(event.currentTarget);
       var file = input[0].files[0];
       var reader = new FileReader();
       reader.onload = function(e){
           image_base64 = e.target.result;
           preview.attr("src", image_base64);
       };
       reader.readAsDataURL(file);
    });
});

在Mozilla文档中,您有另一个例子(肯定更健壮)。此解决方案应与Safari(版本6.0+)一起使用。

And in the Mozilla Documentation, you have another example (surely more robust). This solution should work with Safari (version 6.0+).

这是我知道在提交表单之前预览图像的唯一方法,但我认为这是一种非常常见的方式。当然它与Ruby On Rails无关,因为我们在这里只使用Javascript ...仅使用Rails是不可能的,因为你必须在渲染之前上传图像。 (由于Rails是服务器端,我认为你完全理解为什么。:))

This is the only way I know to preview an image prior to submitting a form, but I think it is quite a common way. Of course it has nothing to do with Ruby On Rails as we only use Javascript here... It would be impossible to do it using Rails only as you would have to upload the image before rendering it. (As Rails is server side, I think you perfectly understand why. :) )

这篇关于Rails 3:上传前预览图像的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆