【问题标题】:How to display an image immediately after selecting it with ng2-file-upload?使用 ng2-file-upload 选择图像后如何立即显示图像?
【发布时间】:2017-01-05 09:20:31
【问题描述】:

我正在使用 angular2 构建一个站点并使用 ng2-file-upload 库 ng2-file-upload 我想在选择后立即在我的网站上显示图像。这个库怎么可能?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以监听onAfterAddingFile 事件并为本地 blob 创建 url:

    this.uploader = new FileUploader({url: '/your/url' });
    this.uploader.onAfterAddingFile = (fileItem) => {
        let url = (window.URL) ? window.URL.createObjectURL(fileItem._file) : (window as any).webkitURL.createObjectURL(fileItem._file);
        this.localImageUrl = url
    }
    

    现在您必须使用的img src 存储在this.localImageUrl 中。问题是当你尝试在 DOM 中使用它时,Angular 会将它标记为不安全。为了克服这个问题,你需要导入DomSanitizer

    import { DomSanitizer } from '@angular/platform-browser';
    

    并将其注入到组件的构造函数中:

    export class MyComponent {
        (...)
        constructor(public sanitizer:DomSanitizer) {
        (...)
        }
    

    最后,在模板中添加 img 的地方,使用 sanitizer 信任 url:

    <img [src]="sanitizer.bypassSecurityTrustUrl(localImageUrl)">
    

    【讨论】:

    • 在构造函数中使用 private sanitizer:DomSanitizer 不会向页面公开 sanitizer 变量。应该是public sanitizer:DomSanitizer
    • 它确实预览了图像,但是然后重新加载了 Angular 应用程序,这个问题有什么解决方案吗?
    【解决方案2】:

    遵循以下简单的解决方案

    import { DomSanitizer} from '@angular/platform-browser';
        ...
        public previewPath: any;
        ....
        constructor(private sanitizer: DomSanitizer) {
           this.uploader.onAfterAddingFile = (fileItem) => {
              this.previewPath = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(fileItem._file)));
            }
        }
    

    在html中

     <img [src]="previewPath " alt="Avatar" class="contribution-image">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2019-05-09
      • 2018-05-30
      • 2018-04-25
      • 2014-01-22
      • 2020-11-13
      相关资源
      最近更新 更多