Agular2 + typescript + file upload

前端 未结 1 1283
野的像风
野的像风 2021-02-14 16:50

I am creating an angular2 project, in which my requirement is to upload a file and send some parameters from client to server(Spring Rest Server). I have tried Formdata Interfac

相关标签:
1条回答
  • 2021-02-14 17:24

    Your HTML should be:

    <input id="file-field" name="file-field" (change)="uploadFile($event)" type="file" accept=".png,.jpg,.jpeg">
    

    So you will get file in component as:

    uploadFile(event) {
      let files = event.target.files;
      if (files.length > 0) {
        console.log(file); // You will see the file
        this.service.uploadFile(file);
      }
    }
    

    And in service:

    uploadFile(file) {
      let formData: FormData = new FormData();
      formData.append('file', file, file.name);
    
      this.http.post(url, formData, request_options)
    }
    

    Then you will get file in with file key in request data.

    0 讨论(0)
提交回复
热议问题