【问题标题】:Saving a file on the client side of my React application在我的 React 应用程序的客户端保存文件
【发布时间】:2019-02-08 16:48:44
【问题描述】:

我正在尝试在我的 react 应用程序的客户端保存一个文件。 数据是从我的名为 DownloadDocument 的 API 控制器获得的。 我从我的 DownloadDocument 方法返回 FileSreamResult。 FileStreamResult 读取数据并将其写入 react API 中的响应。 网络选项卡得到响应,但是当我记录响应时,我得到一个空响应。 我正在使用文件保护程序来尝试保存文件。 https://www.npmjs.com/package/file-saver.

是否有人对问题所在或是否有更好的解决方法有任何建议?

我在控制器中的操作:

我遇到的问题是我对 react api 的响应返回 null。

[HttpGet("{documentId}")]
    [AcceptVerbs("OPTIONS", "GET")]
    [AllowAnonymous]
    public async Task<IActionResult> DownloadDocument(int documentId)
    {
      if (documentId != 0)
      {
        var document = await service.DownloadDocumentAsync(documentId);

        var documentResponse = File(document, "application/octet-stream");             
        return documentResponse;
      }
      return BadRequest("Document id is not valid");
    }

反应应用程序。

api.indexes.downloadDocument(clones)
    .then(response=>{
    console.log(response)
    let FileSaver = require('file-saver');
    let blob = new Blob([response], {type: "application/octet-stream"});
    let filename ="testdownload"
    FileSaver.saveAs(blob, filename)

感谢您的帮助。

【问题讨论】:

    标签: javascript c# reactjs


    【解决方案1】:

    我需要将此添加到标题中。 响应类型:'blob'

    这篇文章解释得很好 https://medium.com/@fakiolinho/handle-blobs-requests-with-axios-the-right-way-bb905bdb1c04

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2015-08-21
      • 2014-04-19
      相关资源
      最近更新 更多