javascript - 使用响应式(Reactive)形式将多个文件(图像、文件文本等)上传到服务器

标签 javascript angular ionic2 ionic3

嗨,我想上传多个文件并将它们发送到服务器:使用 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/

相关文章:

javascript - 无法在 Firebug 中设置断点

JavaScript:存储 cookie

javascript - 如何设置是或否单选的计数器,该计数器在提交时递增?

angular - 参数 'error' 隐式具有 'any' 类型

css - 如何在 Ionic 2 中将文本换行到 <ion-segment-button> 中

javascript - 使用变量在 node.js 应用程序中执行正则表达式 Mongo 搜索

输入的 Angular 和 Jasmine 单元测试更改事件[类型 ="file"]

javascript - 应用 array.filter 时,传递给函数的数组引用会丢失

html - ionic2 contenteditable div 不适用于 iOS 设备

android - 如何播放 Ionic2 附带的音频