Angular 帮助如何通过 HTTP 提交文件 Post

Angular help how to submit a file via HTTP Post

我需要一些帮助来弄清楚我在尝试通过表单数据将 pdf/file 从 angular 发送到我的后端时遗漏了什么,但我在这样做时遇到了一些问题我通过 POST 按下提交时出现错误(附有错误和代码)。如果有任何帮助,我将不胜感激!

component.ts

handleFileInput(file: File) {
this.fileToUpload = file;
}

basicUpload(files: File){
var formData = new FormData();
formData.append('file', files)

this.execSummaryUploadService.upload(formData)
 .subscribe(event => {  
})
}

HTML <div class="form-group"> <label for="file">Choose File</label> <input type="file" id="file" (change)="handleFileInput($event.target.files)"> <button mat-fab color="primary" (click)="basicUpload()">Send</button> </div>

上传服务

constructor(private http: HttpClient) { }

public upload(formData) {
 return this.http.post<any>(this.URL, formData, {
   reportProgress: true,
   observe: 'events'
 });
}

错误

 core.js:15714 ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request"

从事件中获取单个文件

  <input #file type="file"
         id="file"
         (change)="handleFileInput($event)">
  <button (click)="upload()">UPLOAD</button>
    export class AppComponent  {

      @ViewChild('file', { static: true }) fileInput: ElementRef;
      fileToUpload: File;

      constructor(private uploadService: UploadService) {
      }

      handleFileInput(event) {
        const fileList: FileList = event.target.files;
        console.log(fileList);
        if (fileList.length > 0) {
          const file: File = fileList[0];
          this.fileToUpload = file;
        }
      }

      public upload() {
        return this.uploadService.upload(this.fileToUpload)
          .pipe(
            finalize(() => {
              this.fileInput.nativeElement.value = null;
            })
          )
          .subscribe(() => {
          });
      }
    }

您可以试试下面的上传服务

  @Injectable()
  export class UploadService {
    constructor(private http: HttpClient) {
    }

    upload(data: File) {
      let url = '';

      const content = new FormData();
      if (data !== null && data !== undefined) {
        content.append("file", data, "file");
      }

      let options : any = {
        body: content,
        observe: "response",
        responseType: "blob",           
        headers: new HttpHeaders({
          "Accept": "application/json"
        })
      };

      return this.http.request("post", url, options);
    }
  }

some example 但它绑定到 .net 后端可能与你的不匹配