How to Upload File from Angular to ASP.NET Core Web API

前端 未结 2 981
旧时难觅i
旧时难觅i 2021-01-17 16:09

Similar questions have been asked but after looking through all of those and many blog posts on the subject I have not been able to figure this out so please forgive me.

2条回答
  •  日久生厌
    2021-01-17 16:21

    my BlogController looks like this:

    [HttpPost]
    
    public async Task> PostBlog([FromForm]PostBlogModel blogModel)
    

    It seems that you'd like to pass data using form-data, to achieve it, you can refer to the following code sample.

    .component.html

    .component.ts

    selectedFile: File = null;
    private newBlogForm: FormGroup;
    constructor(private http: HttpClient) { }
    
    ngOnInit() {
      this.newBlogForm = new FormGroup({
        Name: new FormControl(null),
        TileImage: new FormControl(null)
      });
    }
    
    onSelectFile(fileInput: any) {
      this.selectedFile = fileInput.target.files[0];
    }
    
    onSubmit(data) {
      
      const formData = new FormData();
      formData.append('Name', data.Name);
      formData.append('TileImage', this.selectedFile);
    
      this.http.post('your_url_here', formData)
      .subscribe(res => {
    
        alert('Uploaded!!');
      });
    
      this.newBlogForm.reset();
    }
    

    Test Result

提交回复
热议问题