首页 > 解决方案 > Angular 帮助如何通过 HTTP Post 提交文件

问题描述

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

组件.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"

标签: angularangular-forms

解决方案


从事件中获取单个文件

  <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);
    }
  }

一些示例,但它与.net 后端相关,可能与您的不匹配


推荐阅读