Angular 5沿其他对象的属性上传文件

问题描述 投票:3回答:2

我想将文件作为属性的一部分上传到表单中的对象。我已经研究过这个,但大多数文档都指的是只处理文件的服务。在我的场景中,我有一个表单,其中除了其他文本输入和日期选择器之外,还有一个文件上载字段。那你怎么处理那个?

<mat-form-field>
    <input matInput placeholder="Start date" name="startdate">
    <mat-datepicker-toggle matSuffix [for]="SDpicker"></mat-datepicker-toggle>
    <mat-datepicker #SDpicker ngDefaultControl (selectedChanged)="onStartDateChange($event)"></mat-datepicker>
  </mat-form-field>
  <mat-form-field>
    <input matInput placeholder="End date" name="enddate">
    <mat-datepicker-toggle matSuffix [for]="EDpicker"></mat-datepicker-toggle>
    <mat-datepicker #EDpicker ></mat-datepicker>
  </mat-form-field>
  <mat-form-field>
    <input matInput placeholder="No. of days" name="noofdays">
  </mat-form-field>
  <label for="uploadAttachment" class="upload-file">
    <mat-icon>cloud_upload</mat-icon>
  </label>
  <input type="file" id="leaveapplication.attachment" class="hidden-input" (change)="onFileChange($event)" accept="image/jpeg, .jpeg, image/png, .png, image/pjpeg, .jpg, application/pdf" #fileInput>
  <button mat-button (click)="clearFile()">clear file</button>

这是服务:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class LeaveapplicationService {

  constructor(private http: Http) { }
  getLeaveApplications() {
    return this.http.get('api/LeaveApplications/Get').map(res => res.json());
  }

  create(leaveapplication) {
    return this.http.post('/api/LeaveApplications', leaveapplication).map(res => res.json());
  }

}

API是核心2 web api

获取组件内部文件的方法应该是这样的:

 onFileChange(event) {
    let reader = new FileReader();
    if (event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.form.get('leaveapplication.attachment').setValue({
          filename: file.name,
          filetype: file.type,
          value: reader.result.split(',')[1]
        })
      };
    }
  }

但是如何将附加文件绑定到leaveapplication obj的属性以将其作为一个整体传递给API?

angular typescript asp.net-core-webapi ng-file-upload
2个回答
0
投票

您需要将文件作为formData传递给API中的对象。像下面的东西。

onFileChange(event) {
    let reader = new FileReader();
    if (event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      const data= new Blob([file], { type: "application/text" });
      const formData = new FormData();
      formData.append("inputFile", jsonData);
      };
    }
  }

0
投票

您需要使用表单数据通过多部分请求上载文件。

public create(leaveapplication, file:File) : Observable<any>{
    let formData: FormData = new FormData();
    formData.append('data', JSON.stringify(leaveapplication));
    formData.append('file', file, file.name);
    return this.http.post('/api/LeaveApplications' , formData)
        .map(res => {return res.json()});
}

使用此方法,您的附件不再是“离开应用程序”的属性。

如果您确实需要将附件作为属性,则可以尝试使用base64编码。

© www.soinside.com 2019 - 2024. All rights reserved.