使用React从FileStream返回下载文件

时间:2019-10-18 18:47:03

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

嗨,我有一个下图所示的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;
    }

1 个答案:

答案 0 :(得分:0)

最后也通过使用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");
    }

然后我的客户端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给予的所有支持-非常感谢。