简体   繁体   中英

How to receive a file from ASP.NET Core Web API from Angular service and display in a different chrome tab

I have a Web API written in .NET Core which returns a file as follows:

[Authorize]
[HttpGet("{id}")]
public async Task<IActionResult> GetFile(int id)
{
    var response = await _fileService.GetFile(id);

    Response.Clear();

    return File(response.FileByteArray, response.FileType, response.FileName);
}

public async Task<FileResponseDTO> GetFile(int fileId)
{
    using (var unitOfWork = _unitOfWorkFactory.CreateUnitOfWork())
    {
        var response = new FileResponseDTO();
        var file = await unitOfWork.FileRepository.GetFile(fileId);

        if (file != null)
        {
            string filePath = GetFilePath(file.FileName);

            response.FileByteArray = System.IO.File.ReadAllBytes(filePath);
            response.FileName = file.FileName;
            response.FileType = file.FileType; ;
        }

        return response;
    }
}

It returns a file as follows:

在此处输入图像描述

Now I want to consume the service using Angular with the following function in a service:

getFile(id: number): Observable<File> {
    return this.http.get<File>(
        this.uri + `/file/${id}`
    );
}

Can someone please help how to consume this api and also how can I display the image/file in Chrome?

Thanks.

You are returning a file, which will work for the downloading file. Instead of returning file, save the file a location on your project and return the path to angular. And then show the path to your image src.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM