1

我是角度的新手。我在提交包含文件上传的表单时遇到问题。文件上传是文件。提交表单时,studentImage 丢失。需要帮助在表单数据中附加文件 ID?我只想通过 studentImage id 来形成数据。

这是我在这里使用的rest api:

{
    "studentName": "xyz",
    "studentCurrentStatus": "Studying in DU",
    "studentFeedback": "abcabc abc",
    "studentBatch": "2019",
    "studentImage": {
        "id": 1
    }
}

 onSelectFile(event) {
    const file = event.target.files[0];
    console.log(file);
    this.userProfile = file;
  }

  uploadFile() {
    const formData = new FormData();
    formData.append('file', this.userProfile);
    this.fileService.saveFile(formData).subscribe((res) => {
      console.log(res);
      // const responseJSON = JSON.parse(res);
      this.imageId = res.id;
      console.log(this.imageId);
    });
  }

  saveNewTestimonial(item: Testimonial) {

    console.log(this.testimonial);
    const formData = new FormData();

    formData.append('studentImage', this.imageId);
    this.testimonialService.saveTestimonial(formData)
      .subscribe((response) => {
        console.log(response);
      });

形式:

  <h1>Add Student Testimonial</h1>
    <form >

      <div class="form-group">
        <label for="studentName">Student's Name</label>
        <input type="text" class="form-control" id="studentName" required>
      </div>

      <div class="form-group">
        <label for="studentBatch">Student's Batch</label>
        <input type="text" class="form-control" id="studentBatch">
      </div>

      <div class="form-group">
        <label for="studentCurrentStatus">Student's Current Status</label>
        <input type="text" class="form-control" id="studentCurrentStatus">
      </div>

      <div class="form-group">
        <label for="studentFeedback">Student's Feedback</label>
        <textarea type="text" class="form-control" id="studentFeedback"></textarea>
      </div>

      <div class="form-group">
        <label for="studentImage">Student's Photo</label>
        <input type="file" class="form-control-file" id="studentImage" accept="image/*" (change)="onSelectFile($event)" #fileInput>
        <button type="button" class="btn btn-success" (click)="uploadFile()">Upload File</button>
      </div>

      <button type="submit" class="btn btn-success" (click)="saveNewTestimonial(testimonial)">Submit</button>

    </form>
4

0 回答 0