使用 React 从 FileStream 返回下载文件

Abd*_*dul 4 javascript asp.net-web-api reactjs

您好,我有一个如下图所示的 Web api - 返回 HttpResponseMessage,我将 fileStream 作为其内容重新设置,当我尝试在控制台上检索或将其记录为 console.log(response.data) 时,它会显示一些其他信息,但是不是流信息或数组或任何此类内容。有人可以帮助我如何使用 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;
    }
Run Code Online (Sandbox Code Playgroud)

Abd*_*dul 6

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

        [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");
    }
Run Code Online (Sandbox Code Playgroud)

然后我的客户端 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);
        });
};
Run Code Online (Sandbox Code Playgroud)

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