如何在同一组件Angular4中选择和显示PDF和图像文件

时间:2018-12-19 15:26:28

标签: angular typescript angular6

我是angular4的新手,我试图在组件中显示pdf文件和图像文件。

在这种情况下,我面临以下问题。

每当我选择一个图像时,它都会显示,但是当我选择一个pdf文件时,所选的图像会被替换,并且pdf文件也不会显示。

我已将代码放入stackblitz中: https://stackblitz.com/edit/angular-rq5ro5?file=src%2Fapp%2Fquestions-stepper%2Fquestions-stepper.component.html

谁能帮我解决这个问题。

HTML

<!-- Image File -->

<button class="col-sm-12 stylings" 
mat-raised-button (click)="file.click()">{{caption}}</button>
<input hidden type="file" accept="image/*" #file onclick="this.value = null" (change)="onSelectFile($event)">
<mat-card class="col-sm-12" style="padding:4px">
<div style="display: flex;align-items: center;justify-content: center;">
<img [src]="selectedImage" class="img-responsive img" /></div>
</mat-card>

  <!-- Pdf File -->

  <button class="col-sm-12 stylings" 
mat-raised-button (click)="file.click()">{{captionPdf}}</button>
<input hidden type='application/pdf' accept="application/pdf" #file1 onclick="this.value = null" (change)="onSelectPdfFile($event)">
<mat-card class="col-sm-12" style="padding:4px">
<div style="display: flex;align-items: center;justify-content: center;">
<img [src]="selectedPdf" class="img-responsive img" /></div>
</mat-card>

打字稿

 onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      this.imageToUpload = event.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(this.imageToUpload);
      reader.onload = e => this.selectedImage = reader.result.toString();
      this.caption = event.target.files[0].name;
    }
  }

onSelectPdfFile(event) {
    if (event.target.files && event.target.files[0]) {
      this.imageToUpload = event.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(this.imageToUpload);
      reader.onload = e => this.selectedPdf = reader.result.toString();
      this.caption = event.target.files[0].name;
    }
  }

1 个答案:

答案 0 :(得分:0)

在PDF部分下,您需要使用file1.click()。还要更改输入类型=“文件”。

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "module": "commonjs",
    "target": "esnext",
    "jsx": "react",
    "sourceMap": false,
    "experimentalDecorators": true,
    "noImplicitUseStrict": true,
    "removeComments": true,
    "moduleResolution": "node",
    "lib": [
      "es2017",
      "dom"
    ],
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "out",
    ".next"
  ]
}

您可以用来预览PDF文档。

<button class="col-sm-12 stylings" 
mat-raised-button (click)="file1.click()">{{captionPdf}}</button>
<input hidden type='file' accept="application/pdf" #file1 onclick="this.value = null" (change)="onSelectPdfFile($event)">

StackBlitz:https://stackblitz.com/edit/angular-pcirtt?file=src%2Fapp%2Fquestions-stepper%2Fquestions-stepper.component.html