【问题标题】:AngularJS image previewAngularJS 图像预览
【发布时间】:2016-04-10 02:57:03
【问题描述】:

我有以下输入文件:

<div class="col s12">
     <h6>Foto</h6>
     <div class="file-field input-field">
          <div class="btn pink darken-2 waves-effect waves-light">
               <span>Archivo</span>
               <input type="file" name="image" id="image"
               file-model="picture.image" custom-on-change="renderPreview">
           </div>
           <div class="file-path-wrapper">
               <input class="file-path" type="text" readonly>
           </div>
    </div>
</div>

当指令custom-on-change 触发时,我从输入中获取文件(console.log() 在这里工作)所以我接下来要做的是预览我刚刚选择的图像:

$scope.renderPreview = function(event){
      var picture = event.target.files;
      console.log(picture);
      $('#image-preview').attr('src', picture);
}

应该放在这里:

<h5 class="center-align">Vista Preliminar</h5>
<div class="col s6 offset-s3">
     <div class="image-preview-container">
          <img id="image-preview" class="z-depth-2">
     </div>
</div>

但是,没有渲染图像。我一直在尝试寻找解决方案,人们总是将您发送到那些 angular 文件上传插件。我不想将这些插件用于像这样的简单任务。

有没有一种方法可以渲染图片,以便用户在上传之前可以看到它?

编辑

我的自定义更改指令:

angular.module('sccateringApp')
  .directive('customOnChange', function () {
      return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var onChangeHandler = scope.$eval(attrs.customOnChange);
        element.bind('change', onChangeHandler);
      }
    };
  });

【问题讨论】:

  • 什么是 console.log(picture) 的控制台日志;
  • FileList {0: File}0: Filelength: 1__proto__: FileList [object%20FileList]:1 GET http://localhost:9000/[object%20FileList] 404 (Not Found) 这就是 console.log() @RohanPawar 上显示的内容

标签: javascript angularjs image


【解决方案1】:

在您的代码中,var picture 是文件数组,所以使用索引来显示图像

$scope.renderPreview = function(event){
      var pictures = event.target.files;
      $('#image-preview').attr('src', pictures[0]);
}

根据@Hanlet Escaño 的建议 试试下面的代码

$scope.renderPreview = function (event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#image-preview').attr('src', e.target.result);
    }

    reader.readAsDataURL(event.target.files[0]);
  }
};

【讨论】:

  • 如果你想预览你的文件,你将需要HTML5's FileReader API(或类似的技术)(正如我在上面添加的副本中所解释的那样)。
  • @HanletEscaño 他的日志显示文件数组为空
  • 不完全是我使用的代码,但肯定涉及fileReader,我以前从未使用过它,也从未有必要使用图像预览sn-p,因为我经常使用插件为了这。非常感谢!
猜你喜欢
  • 2017-01-17
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 2020-05-01
  • 2015-08-01
  • 2015-07-02
  • 2014-12-21
  • 2017-03-13
相关资源
最近更新 更多