首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Angular 6- POSTing a file onSubmit

Angular 6- POSTing a file onSubmit
EN

Stack Overflow用户
提问于 2018-07-26 03:59:36
回答 1查看 715关注 0票数 0

这就是我目前所拥有的。

edit-client.component.html

代码语言:javascript
复制
<form class="form-horizontal" #clientForm="ngForm" (ngSubmit)="onSubmit(clientForm)">

...

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.jpg,.jpeg,.png">

...

<input type="submit" value="Submit" class="btn btn-primary btn-block" [disabled]="!disableBtn">

edit-client.component.ts

下面是fileChange函数,上传到一个通用的接口上。

代码语言:javascript
复制
    fileChange(event) {

      const httpOptions = {
        headers: new HttpHeaders({
          'Authorization': `${this.authBearer}`,
        })
      };

      let fileList: FileList = event.target.files;
      if(fileList.length > 0) {
        let file: File = this.fileList[0];
        let formData:FormData = new FormData();
        formData.append('files', file, file.name);

        this.http.post(`${this.apiEndPoint}`, formData, httpOptions)
          .subscribe( res => {
            this.client.fileAttach = res[0].url;
            this.client.fileAttachName = res[0].name;
          })
      }
    }

下面是onSubmit函数,它在firebase上发布信息

代码语言:javascript
复制
    onSubmit({value, valid}: {value: Client, valid: boolean}) {
      console.log(this.downloadURL);
      if (!valid) {
        this.toasterService.pop('error', 'Error', 'Please fill the form correctly');
      } else {
        // Add id to client
        value.id = this.id;
        value.fileAttach = this.client.fileAttach;
        value.fileAttachName = this.client.fileAttachName;
        // update client
        this.clientService.updateClient(value);

        this.toasterService.pop('success', 'Sucess!', this.client.firstName + ' ' + this.client.lastName + ' Updated');
      }
    }

如何让文件在我点击提交时上传,而不是在我选择文件时上传?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-26 04:06:26

onChange,则将其保存到类中的变量中

因此,不是:

代码语言:javascript
复制
let file: File = this.fileList[0];

您需要:

代码语言:javascript
复制
file: File;

constructor() {}

……

代码语言:javascript
复制
this.file = this.fileList[0];

Then, on submit, you do the http logic:

submit() {
    let formData:FormData = new FormData();
    formData.append('files', this.file, this.file.name);

    this.http.post(`${this.apiEndPoint}`, formData, httpOptions)
      .subscribe( res => {
        this.client.fileAttach = res[0].url;
        this.client.fileAttachName = res[0].name;
      })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51526793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档