【问题标题】:How to preview picture stored in the fake path?如何预览存储在假路径中的图片?
【发布时间】:2014-01-29 04:24:21
【问题描述】:

我正在制作上传表单。这是jquery函数:

 $("#dropbrows").click(function(){
  $("#browse").trigger("click");
      $("#browse").change(function (){

  var test = $("#browse").val();

  $("#userpic").append("<a>'"+test+"'</a><img src='"+test+"' width='30' height='30' />");


});
   });

和 HTML

        <ul id="userpic" class="userpic">

            <!-- The file uploads will be shown here -->
        </ul>

正如您所见,我要做的是在选择图片时制作一个小缩略图,图片存储在“C:\fakepath\1518290_611410375580021_371786666_n.jpg”中,浏览器将图片的完整路径显示为“C:\ fakepath\1518290_611410375580021_371786666_n.jpg' 但不是缩略图,而是显示一个问号。我猜是因为它无法在路径中找到物理图片文件。

问题是,如何让缩略图显示图片?我在这里做错了什么?

非常感谢。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    试试这个,

    $(function(){
        $("#browse").change(function () {
           var files = this.files;
           var reader = new FileReader();
           var name=this.value;
           reader.onload = function (e) {
              $("#userpic").append("<a>'"+name+"'</a><img src='"+e.target.result+"' width='30' height='30' />");
           };
           reader.readAsDataURL(files[0]);
        });
    });
    

    另外如果您将userpic 用作ul,则将li 附加到您的string 中,

    $("#userpic").append("<li>anchor and image here</li>");
    

    Live Demo

    【讨论】:

    • Rohan 非常感谢,您的代码显示了缩略图,但是当我将 test 更改为 e 时,我得到的不是文件名,而是 'data:image/jpeg;base64,/9j/4AAQS....' .target.result 或当我更改为“阅读器”时获取“对象”如何显示文件名?我正在隐藏
    • 我的demo 中没有看到任何object,它只显示了图像的name
    • 现在它再次显示假路径,就像在我的代码中一样,我试图拆分 'C:\fakepath\ 但使用 .split( )
    • 您使用的是哪个浏览器?我在Firefox v 26 测试过。
    【解决方案2】:

    要创建上传文件的图像预览,请查看以下链接中的答案:

    Preview an image before it is uploaded

    这是该链接的公认答案:

    Please take a look at the sample JS code below:
    
    function readURL(input) {
    
        if (input.files && input.files[0]) {
            var reader = new FileReader();
    
            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }
    
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    $("#imgInp").change(function(){
        readURL(this);
    });
    
    and the associated HTML:
    
    <form id="form1" runat="server">
        <input type='file' id="imgInp" />
        <img id="blah" src="#" alt="your image" />
    </form>
    

    以上代码的DEMO

    【讨论】:

      猜你喜欢
      • 2016-12-28
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多