HttpErrorResponse {headers:HttpHeaders,状态:415,statusText:"Unsupported Media Type"

HttpErrorResponse {headers: HttpHeaders, status: 415, statusText: "Unsupported Media Type"

您好,我尝试上传一个 csv 文件并将其转换为 json 数组并传递到网络 api。但是当我点击提交按钮时,我收到了这个错误。谁能帮忙解决这个问题? 谢谢:)

This is my .ts file in angular 在这里,我尝试上传一个csv文件并将其转换为json数组。

    changeListener(event: any) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.myForm.patchValue({
        fileSource: file
      });

      //File reader method
      let reader: FileReader = new FileReader();
      reader.readAsText(file);
      reader.onload = (e) => {
        let csv: any = reader.result;
        let allTextLines = [];
        allTextLines = csv.split(/\r|\n|\r/);
        console.log('CSV: ', csv?.toString());
      }

      //JSON.stringify(file);
    }
  }

  submit() {
    const formData = new FormData();
    formData.append('file', this.myForm.get('fileSource')?.value);

    this.http.post('http://localhost:64233/api/employee', formData)
      .subscribe(res => {
        console.log(res);
        alert('Upload Sussessful');
      })
  }

这是我在 angular

中的 .html 文件
    <form [formGroup]="myForm" (ngSubmit)="submit()">

    <h1 style="text-align: center">File Upload</h1>
    <br /><br />

    <div class="form-group">
        <label for="file">File</label>
        <input class="form-control" formControlName="file" id="file" type="file" class="upload"
            (change)="changeListener($event)" />
    </div>

    <button id="btnSave" class="btn btn-primary" type="submit">Submit</button>

</form>

这是我点击提交按钮时出现的错误

我在邮递员中检查了我的网站 api,它对 json 数组工作正常。如果您能提供帮助,我将不胜感激。谢谢

好吧,我在自言自语。但这是为了帮助别人。

在我的 .ts 文件中,我已经上传了文件并将 csv 文件中的数据作为字符串读取。但是我没有正确地将它转换为 json 数组并将其推送到网络 api.

所以下面是工作代码。这可能不是最完美的,但对我来说效果很好。

这是我在 angular

中的 .ts 文件
  export class FileUploadComponent implements OnInit {

  myForm = new FormGroup({
    file: new FormControl('', [Validators.required])
  });

  ngOnInit(): void {
    this.resetForm();
  }

  constructor(private http: HttpClient, public fileUploadService: FileUploadService,
    private toastr: ToastrService, private router: Router) { }

  obj: any;
  unique: any;
  removeHeader: any;
  // Maximum file size allowed to be uploaded = 1MB
  maxSize: number = 1048576;

  //upload file
  fileUpload(event: any) {
    if (event.target.files && event.target.files.length > 0) {
      // Don't allow file sizes over 1MB
      if (event.target.files[0].size < this.maxSize) {
        const file = event.target.files[0];
        console.log(file);

        //File reader method
        let reader: FileReader = new FileReader();
        reader.readAsText(file);
        reader.onload = (e) => {
          let csv: any = reader.result;
          let res: any[] = csv.split("\n");

          //remove first element of the array
          res.shift();

          let jsonArray: any = [];

          res.forEach(item => {
            let singlePerson = item.split(",");
            let singleObject = { employeeid: singlePerson[0], firstname: singlePerson[1], lastname: singlePerson[2], address: singlePerson[3] }
            jsonArray.push(singleObject);
          })
          this.obj = jsonArray;

          //check duplicates in csv file, remove, and return unique records
          let unique = this.obj
            .map((e: { [x: string]: any; }) => e['employeeid'])
            .map((e: any, i: any, final: string | any[]) => final.indexOf(e) === i && i)
            .filter((obje: string | number) => this.obj[obje])
            .map((e: string | number) => this.obj[e]);

          this.obj = unique;
        }
      }
      else {
        // Display error message
        this.toastr.error("File is too large to upload");
      }
    }
  }

  resetForm() {
    this.myForm.reset();
  }

  submit() {
    this.fileUploadService.postFileUpload(this.obj);
    this.resetForm();
  }
}

这是我的html文件

<br /><br />

<form [formGroup]="myForm">
  <h1 style="text-align: center">File Upload</h1>
  <br /><br />

  <div class="form-group">
    <label for="file" style="font-size: 25px">File</label>
    <input
      class="form-control"
      formControlName="file"
      type="file"
      accept=".csv"
      class="upload"
      (change)="fileUpload($event)"
    />
  </div>

  <div class="form-group">
    <label> Please Upload a CSV or Text file of size less than 1MB </label>
  </div>

  <button class="btn btn-primary" type="submit" (click)="submit()">
    Submit
  </button>
</form>

这是我的服务class

export class FileUploadService {

  messages: string[] = [];

  constructor(private http: HttpClient, private toastr: ToastrService) { }

  readonly baseURL = 'http://localhost:64233/api/employee';

  myForm = new FormGroup({
    file: new FormControl('', [Validators.required])
  });

  formData: FileUpload = new FileUpload();

  //method for post request
  postFileUpload(body: any) {
    const requestOptions = { headers: new HttpHeaders({ 'content-type': "application/json" }) };
    return this.http.post(this.baseURL, body, requestOptions)
      .subscribe(
        observer => {
          this.toastr.success("File Uploaded Succesfully");
          this.resetForm();
        },
        err => {
          if (err.status == 500)
            this.toastr.error("Empty File");

          else
          this.toastr.error("Please upload a file");
            //console.log(err);
          /* (error) => {
            console.log(error); */
          //throw new Error(error);
        });
  }

  resetForm() {
    this.myForm.reset();
    this.formData = new FileUpload();
  }
}

此处显示警报我使用了烤面包机