带有表单内容的Angular 6文件上传

时间:2018-09-08 11:13:55

标签: angular6

我创建了一个页面,其中包含不同的输入元素以及文件上传。在使用Angular 6保存包含多个文件的表单以及表单输入元素的同时,在控制台的“网络”选项卡中的http服务中,文件对象为空{}。

这是我的代码:

onFileChanged(event) {    
    this.selectedFiles = event.target.files; 
    const uploadData = new FormData();
    uploadData.append('myFile', this.selectedFiles, this.selectedFiles[0].name);    
    this.createFormData.attachment = uploadData;   
};

有人可以提供样品帮助我吗?

2 个答案:

答案 0 :(得分:3)

这是服务中上传方法的示例。将文件和输入值从组件传递到服务,创建formData,在文件上循环,并将每个文件附加到formData并与输入值相同。

  upload(files, inputs) {
    let formData  = new FormData();

    files.map((file) => {
      formData.append('file', file);
    });

    inputs.map((input) => {
      formData.append(`${input.name}`, input.value);
    });

    return this.http.post(`some/api/upload`, formData)
      .pipe(map((res) => res.data));

}

在此示例中,您的请求应包含所有文件和输入数组,如果您需要一些特殊的标头,请在post方法中的formData之后添加它(在我的情况下,我将在拦截器中处理标头)。

  upload(files, inputs) {
    let formData  = new FormData();

    files.map((file) => {
      formData.append('file', file);
    });

    inputs.map((input) => {
      formData.append(`${input.name}`, input.value);
    });

    const headers   = new HttpHeaders({
      'Accept': 'application/json'
    });

    const options = { headers: headers };

    return this.http.post(`some/api/upload`, formData, options)
      .pipe(map((res) => res.data));
  }

答案 1 :(得分:-1)

使用npm的ng2-file-upload(在这种情况下,使用fontAwsome-icon)查看以下示例。

myFileUploadForm.component.html:

                  <!-- file upload -->
                  <input #fileToUpload type="file" style="display:none;" ng2FileSelect (change)="onFileChanged($event)" [uploader]="uploader"
                    name="customerFile" id="customerFile" class="customerFile" />
                  <a href="javascript:document.getElementById('customerFile').click();">
                    <fa class="ql-upload" *ngIf="buttonDeaktivieren" [title]="'Upload'" [name]="'upload'" [size]="0.9" [border]=false></fa>
                  </a>

myFileUploadForm.component.ts(我将用..省略明显的部分):

import { Component, OnInit, ViewChild, OnDestroy, TemplateRef } from '@angular/core';
import { Subscription, Observable } from '../../../../../node_modules/rxjs';
....
...
import { FileUploader } from 'ng2-file-upload';


@Component({
....
...
..
})

export class myFileUploadFormComponent implements OnInit, OnDestroy {

  public uploader: FileUploader = new FileUploader({ url: 
 'http://localhost:3000/files/uploadFile/', itemAlias: 'customerFile' });

 filesArray = [];

 constructor(
    ...
    ..
    private http: Http
 ) { }

 ngOnInit() {
     ....
     ...
     ..
 }

 // INFO: Function for opening confirm modal when deleting file
 openDeleteFileModal(file) {
     const initialState = {
     file: file
     };
 this.deleteFileModalRef = this.modalService.show(ConfirmFileDeletionComponent, { 
 initialState, class: 'modal-md modal-dialog-centered' });
 }

 // INFO: Handy helper for assigning appropriate file-icon according to extension
 getFilesIcon(file) {
    if (file === 'docx') {
       return 'file-word-o';
    } else if (file === 'jpeg' || file === 'jpg' || file === 'png') {
      return 'image';
    } else if (file === 'pdf') {
      return 'file-pdf-o';
    } else if (file === 'xlsx' || file === 'xls') {
      return 'file-excel-o';
    } else if (file === 'pptx') {
      return 'file-powerpoint-o';
    } else if (file === 'zip') {
      return 'file-archive-o';
    } else {
      return 'file';
    }
  }

  /* INFO : service for downloading the uploaded file */
  downloadFile(filename) {
     this.fileDataService.downloadFile(filename);
  }

  onFileChanged(event) {
     this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
     form.append('id', this.customer.id);
     form.append('customername', this.customer.customername);

  };
  this.uploader.uploadAll();
  }

  ngOnDestroy() {
     this.subscription.unsubscribe();
  }
}

很明显,这是适合我需要的实现(上载的文件与某个客户相关,并且根据扩展名显示图标,并列出以供将来下载或删除),但是我确定您可以完成它通过根据您的需要调整代码并编写相关服务。周末愉快;)