gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:32:56 31 4
gpt4 key购买 nike

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

<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 是 core 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]
})
};
}
}

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

最佳答案

您需要使用 formData 通过多部分请求上传文件。

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()});
}

使用此方法,您的附件不再是'leaveapplication'的属性。

如果你真的需要把你的附件作为属性,你可以试试base64编码。

关于Angular 5 上传文件以及其他对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50267476/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com