【问题标题】:Download file from FileStream return using React使用 React 从 FileStream 返回下载文件
【发布时间】:2019-10-22 02:09:28
【问题描述】:

您好,我有一个如下图所示的 Web api - 返回 HttpResponseMessage,当我尝试检索或在控制台上将其作为 console.log(response.data) 记录时,我正在将 fileStream 作为它的内容返回 它显示了一些其他信息,但不显示流信息或数组或任何此类信息。有人可以帮助我如何读取或下载使用 React 作为流或 FileStream 返回的文件。 我没有使用 jQuery。请提供任何帮助,链接或类似的东西。我可以使用字节数组下载文件,但需要使用 FileStream 来实现,请帮忙?

        [EnableCors("AnotherPolicy")]
    [HttpPost]
    public HttpResponseMessage Post([FromForm] string communityName, [FromForm] string files) //byte[]
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

        var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
        var tFiles = removedInvalidCharsFromFileName.Split(',');
        string rootPath = Configuration.GetValue<string>("ROOT_PATH");
        string communityPath = rootPath + "\\" + communityName;

        byte[] theZipFile = null;
        FileStreamResult fileStreamResult = null;

        using (MemoryStream zipStream = new MemoryStream())
        {
            using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                foreach (string attachment in tFiles)
                {
                    var zipEntry = zip.CreateEntry(attachment);

                    using (FileStream fileStream = new FileStream(communityPath + "\\" + attachment, FileMode.Open))
                    using (Stream entryStream = zipEntry.Open())
                    {
                        fileStream.CopyTo(entryStream);
                    }
                }
            }

            theZipFile = zipStream.ToArray();
            fileStreamResult = new FileStreamResult(zipStream, "application/zip") { FileDownloadName = $"{communityName}.zip" };
            var i = zipStream.Length;
            zipStream.Position = 0;
            var k= zipStream.Length;

            result.Content = new StreamContent(zipStream);
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/zip");
        }

        //return theZipFile;
        return result;
    }

【问题讨论】:

    标签: javascript reactjs asp.net-web-api


    【解决方案1】:

    最后也是通过使用 FileStreamResult 实现的,也许有些人会需要这个,这是我的 API 代码,然后我使用 axios 调用了 post 方法,所以这是我的 React 代码。在 axios 调用 responseType 变成 arraybuffer 并且在 blob 声明中它变成 application/octet-stream 类型,因此它完成了一切,因为我已经导入了文件保护程序,我可以使用它的 saveAs 方法。终于经过许多努力并听到 PM 的尖叫声,是的,它实现了——但这就是任何软件程序员的生活。 这是 C# 的 Web Api 代码:

            [EnableCors("AnotherPolicy")]
        [HttpPost]
        public FileStreamResult Post([FromForm] string communityName, [FromForm] string files) //byte[]
        {
            var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
            var tFiles = removedInvalidCharsFromFileName.Split(',');
            string rootPath = Configuration.GetValue<string>("ROOT_PATH");
            string communityPath = rootPath + "\\" + communityName;
    
            MemoryStream zipStream = new MemoryStream();
    
            using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                foreach (string attachment in tFiles)
                {
                    var zipEntry = zip.CreateEntry(attachment);
    
                    using (FileStream fileStream = new FileStream(communityPath + "\\" + attachment, FileMode.Open))
                    {
                        using (Stream entryStream = zipEntry.Open())
                        {
                            fileStream.CopyTo(entryStream);
                        }
                    }
                }
            }
    
            zipStream.Position = 0;
    
            return File(zipStream, "application/octet-stream");
        }
    

    那么我的客户端 React 代码就在这里:

        handleDownload = (e) => {
        e.preventDefault();
    
        var formData = new FormData();
        formData.append('communityname', this.state.selectedCommunity);
        formData.append('files', JSON.stringify(this.state['checkedFiles']));
    
        //let env='local';        
        let url = clientConfiguration['filesApi.local'];
        //let tempFiles = clientConfiguration[`tempFiles.${env}`];
        //alert(tempFiles);
    
        axios({
            method: 'post',
            responseType: 'arraybuffer', //Force to receive data in a Blob Format
            url: url,
            data: formData
        })
            .then(res => {
                let extension = 'zip';
                let tempFileName = `${this.state['selectedCommunity']}`
                let fileName = `${tempFileName}.${extension}`;
    
                const blob = new Blob([res.data], {
                    type: 'application/octet-stream'
                })
    
                saveAs(blob, fileName)
            })
            .catch(error => {
                console.log(error.message);
            });
    };
    

    单击按钮或提交表单时调用此事件。感谢 SO 给予的所有支持 - 非常感谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 2019-04-24
      • 2021-10-27
      • 2013-09-10
      • 2012-03-14
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多