Не удается загрузить файл из Angular 8 в net core 2.2? - PullRequest
1 голос
/ 16 июня 2020

Angular HTML:

<input #file type="file" name="file" id="file" (click)="handleFileInput($event.target.files)"  />
  <input type="button" value="Save" (click) ="UploadForm()" />  

Angular Код:

 this.formdata = new FormData();
    this.formdata.append('file', this.selectedfile);
    this.httpClient
    .post("https://localhost:44318/api/Trading/FileUpload", this.formdata).subscribe(res=>{ console.log(res) });

. Net Код базового веб-API:

public async Task<SingleResponseModel<Dictionary<string, int>>> FileUploadAsync([FromForm] IFormFile file)
        {
            string createdby = "abcd";
            SingleResponseModel<Dictionary<string, int>> singleResponseModel = new SingleResponseModel<Dictionary<string, int>>();
            FileUploadDocumentModel fileUploadDocumentModel = null;
            string pathToSave = string.Empty;
            string fullPath = string.Empty;

            try
            {
                pathToSave = Path.Combine(Directory.GetCurrentDirectory(), "Documents");
                if (file != null)
                {
                    fullPath = Path.Combine(pathToSave, file.FileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                 }
            }
catch(Exception ex)
{
throw ex;
}
}

Я получаю нулевой объект [FromForm] IFormFile при загрузке файла. Пожалуйста, дайте мне знать, как решить эту проблему?

1 Ответ

0 голосов
/ 16 июня 2020

Похоже, вы не отправляете файлы своему компоненту. Так что попробуйте написать так:

<input #file type="file" name="file" id="file" (click)="handleFileInput(file.files)"  />

Позвольте мне показать пример, как можно загружать файлы.

upload.component. html:

<input type="file" #file placeholder="Choose file" (change)="uploadFile(file.files)" 
            accept="image/x-png,image/gif,image/jpeg" multiple>

upload.component.ts :

public uploadFile = (files) => {
  if (files.length === 0) {
      return;
  }

  const fileToUpload = files[0] as File;
  const formData = new FormData();
  formData.append('file', fileToUpload, fileToUpload.name);

  this.uploadService.uploadFile(formData)
      .subscribe(event => {
          if (event.type === HttpEventType.UploadProgress) {
              this.progress = Math.round(100 * event.loaded / event.total);
          } else if (event.type === HttpEventType.Response) {
              this.message = 'Upload success.';
              this.onUploadFinished.emit({ dbPath: event.body.dbPath});
          }
      });
}

Фактический метод обслуживания :

uploadFile(file: FormData): Observable<any> {
    return this.http.post(`${environment.baseApi}Upload`, 
        file, {reportProgress: true, observe: 'events'})
        .pipe(map(v => v));
}

ASP. NET Основной контроллер :

[HttpPost]
public IActionResult Upload([FromForm] FileDto fileDto)
{
    if (!ModelState.IsValid)
    {
         return BadRequest(ModelState);
    }   

    if (fileDto.File != null)
    {                
        return Ok(new { dbPath = _uploadFileService.UploadFile(fileDto.File ) });
    }

    return BadRequest();
}

и FileDto.cs:

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace eshop.Persistence.Core.Dtos
{
    public class FileDto
    {
        public IFormFile File { get; set; }

        public string FolderPath { get; set; }

        public string FileName { get; set; }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...