【问题标题】:How to make attachment downloadable - Angular如何使附件可下载 - Angular
【发布时间】:2021-02-02 00:06:41
【问题描述】:

我有一个场景,用户可以上传文件 (PDF/PNG) 并显示是否已经上传了任何文件。我能够做上传部分并向用户显示任何文件已经上传。现在我希望用户可以在单击附件时下载是否存在任何上传的文件。大家能给点建议吗?

ts 文件

upload() {
    const fileUpload = this.fileUpload.nativeElement; //* retrieve native DOM element wrapped by ElementRef
    fileUpload.onchange = () => {
      const file = fileUpload.files[0]; // retrieve file
      if (file) {
        const filesize = getFileSizeHelper(file.size); // get file size
        if (filesize <= 2) {
          this.filename = file.name;
          this.uploadFile(file);
        } else {
          this.fileSizeEr.emit(true);
        }
      }
    };
    fileUpload.click(); // open file picker window
  }

  /**
   * method to upload file
   */
  uploadFile(file: any) {
    const formData = new FormData();
    formData.append('file', file, file.name);
    this.myservice.uploadFile(formData).subscribe((res: any) => {
      this.uploadedFile = res;
      this.fileUploadRes.emit(res); //emit response object to parent component
    });
  }

HTML文件

<div class="upload-space" (click)="upload()">
  <mat-icon *ngIf="!doc?.fileName">publish</mat-icon>
  <span *ngIf="!doc?.fileName">
    {{ "PNG and PDF files allowed(max.2MB)" | translate }}
  </span>
  <span *ngIf="doc?.fileName">
    {{ doc.fileName }}
  </span>
  <!-- <span *ngIf="filename">
    {{ filename }}
  </span>-->
  <input
    type="file"
    #fileUpload
    id=""
    name="fileUpload"
    accept="image/*,application/pdf"
    style="display:none;"
  />
</div>

【问题讨论】:

    标签: javascript html angularjs angular


    【解决方案1】:

    我假设您使用的是 blob,因此在创建链接后,无论是否带有 class="button",您都应该简单地在 (click) 事件上绑定一个带有一些标识属性的函数,然后从您的服务器获取它,然后,告诉你的httpget响应类型是blob。

    带有角度的 httpclient 看起来像这样:

    //injected httpService from angular
    this.httpClient.get('your controller', { responseType: blob}).subscribe( response => {
            const a = document.createElement('a'); // get the element
            const objectUrl = URL.createObjectURL(response); //create objecturl
            a.href = objectUrl; //make the <a></a> link's href to this object url
            a.download = 'any name you want to add'; 
            a.click(); //imitate a click on it
            //THE FOLLOWING STATEMENT IS ONLY FOR BE ABLE TO DOWNLOAD IT IN MS EDGE
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(response, 'any name you want to add' + ".pdf");
            }
            URL.revokeObjectURL(objectUrl);
    })
    

    我认为这不是完美的解决方案,但它对我有用。

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2022-08-24
      • 2019-02-27
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多