Получить / загрузить файлы с помощью Angular и .NET Core API - PullRequest
0 голосов
/ 24 октября 2018

Я разрабатываю угловое приложение с .Net Core API и хочу получить изображения с сервера и загрузить их на сервер.

Вот мой угловой сервис:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class FileService {

  constructor(private http: HttpClient) {
  }

  // Method to get a file
  getFile(id: number): Observable<any> {
    const idFile: number = id === null ? 0 : id;
    const requestUrl = 'api/get-image/' + idFile;
    return this.http.get(requestUrl, { responseType: 'blob' });
  }

  // Method to upload a picture
  uploadAvatar(fileList: File[], fileName) {
    if (fileList.length > 0) {
      const file: File = fileList[0];
      const formData: FormData = new FormData();
      formData.append('file', file);
      const requestUrl = 'api/upload';
      this.http.post(requestUrl, formData);
    }
  }
}

И мой контроллер .NET:

[Route("api")]
public class FileController : Controller
{
    [HttpPost("upload")]
    public async Task Upload(IFormFile file)
    {
        if (file == null) throw new Exception("File is null");
        if (file.Length == 0) throw new Exception("File is empty");

        var filePath = Path.Combine(AppConfig.ResourcesPath + file.FileName);
        using (Stream fileStream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }
    }

    [HttpGet("get-image/{id}")]
    [Produces("image/png")]
    public IActionResult GetFile(int id)
    {
        string path = "";
        if (id == 0)
        {
            path = AppConfig.DefaultImgEvent;
        }
        else if (id == -1)
        {
            path = AppConfig.DefaultImgUser;
        }
        else
        {
            Picture picture = _pictureDal.GetById(id);
            path = picture.Path;
        }
        var file = Path.Combine(AppConfig.ResourcesPath, path);
        _logger.LogInformation(LoggingEvents.GetItem, "Get file {0}", file);
        return PhysicalFile(file, "image/png");
    }
}

Для получения у меня ошибка 404:

Не удалось загрузить ресурс: сервер ответил со статусом 404 (Не найдено) [объект% 20Blob]: 1

А для загрузки я не могу попасть в контроллер

Ответы [ 2 ]

0 голосов
/ 24 октября 2018

Я нашел проблему для файла get:

this.fileService.getFile(this.userDetail.picture.id).subscribe((file) => {
    const url = URL.createObjectURL(file);
    this.avatar = this.sanitizer.bypassSecurityTrustUrl(url);
});

Я добавил дезинфицирующее средство ...

Но для файла загрузки это всегда та же проблема, и это неУри проблема.

0 голосов
/ 24 октября 2018

Попробуйте вернуть this.http.get (requestUrl, {responseType: 'blob', params: idFile});И ваш requestUrl должен быть просто 'api / get-image /'

...