嗨,我想上传多个文件并将它们发送到服务器:使用 react 形式: 我在适当的类中定义了它:
this.attachmentsForm = this.formBuilder.group({
attachmentName: ['']
});
在模板 html 中:
<form [formGroup]="attachmentsForm">
<ion-item>
<ion-label floating>
Attachment Name
</ion-label>
<ion-input type="text" formControlName="attachmentName"></ion-input>
</ion-item>
<input class="form-control" #fileInput type='file' (change)="fileChanged($event)">
</form>
在这个类中我使用了这个函数:
fileChanged(event) {
if (event.target.files && event.target.files[0]) {
if (event.target.files[0].size > 512000) {
this.fileValid = false;
let toast = this.toastCtrl.create({
message: 'the file size more than 500kb',
duration: 3000
});
toast.present();
} else {
this.fileValid = true;
}
}
}
那么我怎样才能获取附件的数据:(Base64或者是否有其他解决方案) 提前致谢
最佳答案
请尝试此代码
imageBase64:string;
file: File;
fileChanged($event: any) {
if (event.target.files && event.target.files[0]) {
this.file = event.target.files[0];
if (this.file.size > 512000) {
if (this.file.type.startsWith("image")){
var myReader:FileReader = new FileReader();
myReader.onloadend = (e) => {
this.imageBase64 = myReader.result;
}
myReader.readAsDataURL(this.file);
}else {
Logger.error("must select an image.");
}
} else {
this.fileValid = true;
}
}
}
关于javascript - 使用响应式(Reactive)形式将多个文件(图像、文件文本等)上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44560001/