上传文件是制作存储某种图像数据的表单的重要组成部分。它有助于使用图像上传的应用程序或文件共享。这个文件上传组件使用file.io API来上传文件,并且作为回报,它提供了一个可共享的链接。此外,我们可以将get请求发送到可共享的链接以获取文件,但目前,我们仅关注上载部分,因此我们仅使用post方法。
方法:
- 使用以下命令创建一个新的角度应用程序
ng new angular-file-upload
- 使用cd命令在应用内移动-
cd src/app/
- 生成新的组件文件-
ng g c file-upload/
- 打开src / app文件夹,然后开始编辑app.component.html文件。
- 通过以下命令为文件上传组件创建服务:
ng g s file-upload/
- 打开src / app / file-upload文件夹,然后开始编辑file-upload.component.ts文件。
import { Component, OnInit } from '@angular/core'; import { FileUploadService } from './file-upload.service'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export class FileUploadComponent implements OnInit { // Variable to store shortLink from api response shortLink: string = ""; loading: boolean = false; // Flag variable file: File = null; // Variable to store file // Inject service constructor(private fileUploadService: FileUploadService) { } ngOnInit(): void { } // On file Select onChange(event) { this.file = event.target.files[0]; } // OnClick of button Upload onUpload() { this.loading = !this.loading; console.log(this.file); this.fileUploadService.upload(this.file).subscribe( (event: any) => { if (typeof (event) === 'object') { // Short link via api response this.shortLink = event.link; this.loading = false; // Flag variable } } ); } }
- 打开src / app / file-upload /并开始编辑file-upload.service.ts文件。
import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class FileUploadService { // API url baseApiUrl = "https://file.io" constructor(private http:HttpClient) { } // Returns an observable upload(file):Observable
{ // Create form data const formData = new FormData(); // Store form name as "file" with file data formData.append("file", file, file.name); // Make http post request over api // with formData as req return this.http.post(this.baseApiUrl, formData) } } - 打开src / app / file-upload并开始编辑file-upload.component.html文件。
Visit Here
{{shortLink}}Loading ...
- 打开src / app /并开始编辑app.module.ts文件。
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FileUploadComponent } from './file-upload/file-upload.component'; import { AppComponent } from './app.component'; import {HttpClientModule} from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, FileUploadComponent, ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
- 现在运行此命令以在localhost上提供服务
ng serve
输出:
- 选择文件之前:
- 选择文件并单击按钮后:
- 加载完成后:
- 选择文件之前: