最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download file from FileStream return using React - Stack Overflow

programmeradmin0浏览0评论

Hi I have a web api like in the below picture - returning HttpResponseMessage, I am retutning fileStream as content of it, when I am trying to retrieve or log it on console as console.log(response.data) it shows some other information but not the stream information or array or anything of that sort. Can somebody please help me how can I read or download file that's returned as stream or FileStream using React. I am not using jQuery. Any help please, a link or something of that sort. I could able to download the file using byte array but need to implement using FileStream, any help please?

        [EnableCors("AnotherPolicy")]
    [HttpPost]
    public HttpResponseMessage Post([FromForm] string munityName, [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 munityPath = rootPath + "\\" + munityName;

        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(munityPath + "\\" + attachment, FileMode.Open))
                    using (Stream entryStream = zipEntry.Open())
                    {
                        fileStream.CopyTo(entryStream);
                    }
                }
            }

            theZipFile = zipStream.ToArray();
            fileStreamResult = new FileStreamResult(zipStream, "application/zip") { FileDownloadName = $"{munityName}.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;
    }

Hi I have a web api like in the below picture - returning HttpResponseMessage, I am retutning fileStream as content of it, when I am trying to retrieve or log it on console as console.log(response.data) it shows some other information but not the stream information or array or anything of that sort. Can somebody please help me how can I read or download file that's returned as stream or FileStream using React. I am not using jQuery. Any help please, a link or something of that sort. I could able to download the file using byte array but need to implement using FileStream, any help please?

        [EnableCors("AnotherPolicy")]
    [HttpPost]
    public HttpResponseMessage Post([FromForm] string munityName, [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 munityPath = rootPath + "\\" + munityName;

        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(munityPath + "\\" + attachment, FileMode.Open))
                    using (Stream entryStream = zipEntry.Open())
                    {
                        fileStream.CopyTo(entryStream);
                    }
                }
            }

            theZipFile = zipStream.ToArray();
            fileStreamResult = new FileStreamResult(zipStream, "application/zip") { FileDownloadName = $"{munityName}.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;
    }
Share Improve this question asked Oct 18, 2019 at 18:47 AbdulAbdul 5613 gold badges8 silver badges23 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Finally implemented by using the FileStreamResult as well maybe some people would be needed this, here is my API code and then I made call to the post method using axios, so here is my React code. In the axios call responseType bees arraybuffer and the in the blob declaration it bees the application/octet-stream type, Hence it pletes everything, as I have imported the file-saver, I could able to use saveAs method of it. Finally after many efforts and hearing the screaming from PM, yes it is achieved - but that's the life of any Software Programmer. Here is Web Api code C#:

        [EnableCors("AnotherPolicy")]
    [HttpPost]
    public FileStreamResult Post([FromForm] string munityName, [FromForm] string files) //byte[]
    {
        var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
        var tFiles = removedInvalidCharsFromFileName.Split(',');
        string rootPath = Configuration.GetValue<string>("ROOT_PATH");
        string munityPath = rootPath + "\\" + munityName;

        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(munityPath + "\\" + attachment, FileMode.Open))
                {
                    using (Stream entryStream = zipEntry.Open())
                    {
                        fileStream.CopyTo(entryStream);
                    }
                }
            }
        }

        zipStream.Position = 0;

        return File(zipStream, "application/octet-stream");
    }

Then my client side React code is here:

    handleDownload = (e) => {
    e.preventDefault();

    var formData = new FormData();
    formData.append('munityname', 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);
        });
};

this event is called when button is clicked or form submitted. Thanks for all the support the SO has given - thanks a lot.

发布评论

评论列表(0)

  1. 暂无评论