Angular 9 FormData和PHP多个文件上传示例

分享于 

6分钟阅读

Angular

  繁體

在本教程中,我们将通过示例学习如何使用FormData和PHP实现Angular 9多文件上传。

使用Angular 9,FormData和PHP上传多个文件

对于服务器,我们将使用简单的REST API来接收上传文件,并使用php将它们存储在文件夹中:


<?php

 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Allow-Methods: PUT, GET, POST");
 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

 $uploadFolder = "upload/";
 $files = $_FILES["file"]["name"];
 for ($i = 0; $i < count($files); $i++) {
 $filename=$files[$i];
 $ext = end(explode(".", $filename));
 $original = pathinfo($filename, PATHINFO_FILENAME);
 $fileurl = $original . "-" . date("YmdHis") . "." . $ext;
 move_uploaded_file($_FILES["file"]["tmp_name"][$i], $uploadFolder . $fileurl);
 }
?>

我们使用Angular 9 HttpClient向php服务器发送Http发布请求,上传文件。

步骤1:创建Angular 9项目

打开命令行接口,并运行以下命令初始化新的Angular 9项目:


$ ng new angular-9-upload-file-demo

导入Angular HttpClientModuleFormsModuleReactiveFormsModule

接下来,我们需要在src/app/app.module.ts文件中导入HttpClientModuleFormsModule和ReactiveFormsModule :


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
 declarations: [
 AppComponent
 ],
 imports: [
 BrowserModule,
 HttpClientModule,
 FormsModule,
 ReactiveFormsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

步骤3:创建响应性表单

现在添加一个带有file类型的输入元素的响应性表单。

打开src/app/app.component.html


<h1>Angular 9 Multiple File Upload Example</h1>

<form [formGroup]="uploadForm" (ngSubmit)="submitForm()">

 <div class="form-group">

 <label for="name">Name</label>

 <input 

 formControlName="name"

 id="name" 

 type="text" 

 class="form-control">

 <div *ngIf="f.name.touched && f.name.invalid">

 <div *ngIf="f.name.errors.required">Filename is required</div>

 </div>

 </div>

 <div class="form-group">

 <label for="file">File</label>

 <input 

 formControlName="file"

 id="file" 

 type="file" 

 multiple

 class="form-control"

 (change)="onFileChange($event)">

 <div *ngIf="f.file.touched && f.file.invalid">
 <div *ngIf="f.file.errors.required">Choose a file</div>
 </div>
 </div>
 <button type="submit">Upload</button>

</form>

步骤4:使用formGroupformControl实现Angular响应性表单

现在,实现使用formGroupformControl上传文件的响应性表单。

稍后,从http://localhost:8000/upload.php运行php脚本来接收上传文件,并将它们保存到服务器。

打开src/app/app.component.ts文件,并按如下方式更新它:


import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl, Validators} from '@angular/forms';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 URL="http://localhost:8000/upload.php";
 files:string [] = [];
 uploadForm = new FormGroup({
 name: new FormControl('', [Validators.required, Validators.minLength(3)]),
 file: new FormControl('', [Validators.required])
 });

 constructor(private httpClient: HttpClient) { }

 get f(){
 return this.uploadForm.controls;
 }

 onFileChange(event) {
 for (var i = 0; i < event.target.files.length; i++) { 
 this.files.push(event.target.files[i]);
 }
 }

 submitForm(){

 const formData = new FormData();
 for (var i = 0; i < this.myFiles.length; i++) { 
 formData.append("file[]", this.myFiles[i]);
 } 

 this.httpClient.post(this.URL, formData).subscribe(res => {
 console.log(res);
 alert('Files uploaded Successfully!');
 })
 }
}

最后,使用以下命令启动Angular 9开发服务器:


ng serve

接下来,使用以下命令启动PHP文件上传服务器:


php -S localhost:8000


文件  for  PHP  angular  form  上传