angular-上传图片预览

8次阅读

共计 1298 个字符,预计需要花费 4 分钟才能阅读完成。

在本周的项目中接触到了文件上传的功能,总的说来难度不大,但在第一次使用时仍然碰到了不少的问题,好在全部都解决了。

先说说上传文件

上传文件自然就是 inputtype设置为 file, 需要注意的是这里通过chang 方法传递的值应是 $event.target.files。开始时我就想着用ngModel 去绑定这个值,但打印出来的东西一看就不对, 还多亏黄庭祥告诉我需要用这个。

<input type="file" (change)="fileChange($event.target.files)">
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {fileChange(file: File[]) {console.log(file);
  }
}

打印结果如下,可以看出是一个文件对象的数组

把这个传给后端,保存的事就交给后端了。

只想要图片?

想要固定用户能发送的文件类型?很简单,只需要一个 accpet 属性就好了,比如只想要 .png 的图片

<input type="file" accept="image/png" (change)="fileChange($event.target.files)">

其他类型的文件就看不到了,让我们对比一下。

更多相关操作可以看看这篇文章。

预览图片

用户选完图片忘了自己选的是啥咋办?毕竟可没多少人愿意给图片规规矩矩命名,让用户按名字再去看选的是那张,这无疑是相当不友好的。所以让他能看到自己选的图片的预览无疑是必须的。

代码如下

<input type="file" accept="image/png" (change)="fileChange($event.target.files)">
<img *ngIf="imgURL" [src]="imgURL" >
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public imagePath;
  imgURL: any;
  public message: string;

  fileChange(files) {console.log(files);
    if (files.length === 0) {return;}

    const reader = new FileReader();
    this.imagePath = files;
    reader.readAsDataURL(files[0]);
    reader.onload = () => {this.imgURL = reader.result;};
  }
}

不过我使用 @ViewChild 却始终实现不了,也不知道为啥。

正文完
 0