尝试使用angular 5和asp.net core从数据库下载文件

问题描述 投票:0回答:1

我试图通过id下载已成功上传到数据库的文件。有谁知道为了得到正确的结果需要做些什么?

我有一个FileUpload表,其中包含以下列(与文件相关):

Id = uniqueidentifier,
Content = varbinary,
ContentType = nvarchar, e.g. application/pdf
FileName = nvarchar, e.g. filename.pdf
FileType = tinyint 

这是Controller中的方法。

/// <summary>
/// Download the file from the database by id.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>The file.</returns>
[HttpGet]
public async Task<ActionResult> GetDownloadFile(Guid id)
{
    if (id == null)
    {
        throw new UserFriendlyException("File not found.");
    }
    var file = await _fileUploadRepository.FirstOrDefaultAsync(id);
    var filename = file.FileName.ToString();
    var fileBytes = file.Content;
    return File(fileBytes, file.ContentType,file.FileName);
}

这是试图调用控制器的打字稿,但它不起作用(我只包括相关代码):

constructor(
injector: Injector,
private _fileUploadsServiceProxy: FileUploadsServiceProxy,
private _notifyService: NotifyService,
private _tokenAuth: TokenAuthServiceProxy,
private _activatedRoute: ActivatedRoute,
private _fileDownloadService: FileDownloadService,
private _searchService: SearchService,
private http: Http
) {
super(injector);
}

/// <summary> 
/// Download the file from the database.
/// </summary>
///<param name="file">The file.</param>
downloadFile(file: any): void {
    if (file.fileUpload.id) {
        var headers = new Headers();
        headers.append('Content-Type', file.fileUpload.contentType);
        headers.append('Authorization', 'Bearer ' + abp.auth.getToken());

        this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${file.fileUpload.id}`, {
            headers: headers,
            responseType: ResponseContentType.Blob
        })
            .subscribe(result => {
                saveAs(result.blob(), file.fileUpload.fileName);
                this.notify.success(`Downloaded ${file.fileUpload.fileName} successfully.`);
        });
    }
}
c# asp.net-mvc typescript
1个回答
2
投票

你的C#代码似乎是正确的,但你的TypeScript / Angular代码不会调用你的API的GetDownloadFile动作。

http.get(...)方法返回一个observable,只有在您订阅它时才会触发HTTP请求。

public downloadFile(id: number): void {
  var headers = new Headers();
  headers.append('Content-Type', 'application/octetstream');
  headers.append('Authorization', 'Bearer ' + abp.auth.getToken());

  this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${id}`)
    .subscribe(result => {
      // result contains your file data.
    });
}

现在,您需要保存文件,您可以使用file-saver包。

在项目根目录(package.json所在的位置)中使用以下命令安装软件包

npm install file-saver --save

然后更新您的代码以导入并调用文件保护程序方法来保存您的文件。

import { saveAs } from 'file-saver';

public downloadFile(id: number): void {
  var headers = new Headers();
  headers.append('Content-Type', 'application/octetstream');
  headers.append('Authorization', 'Bearer ' + abp.auth.getToken());

  this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${id}`).subscribe(result => {
    saveAs(result, 'fileName');
  });
}

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.