Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from FileStream return using React

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 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;
    }
like image 340
Abdul Avatar asked Sep 05 '25 03:09

Abdul


1 Answers

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 becomes arraybuffer and the in the blob declaration it becomes the application/octet-stream type, Hence it completes 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 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");
    }

Then my client side React code is here:

    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);
        });
};

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

like image 174
Abdul Avatar answered Sep 08 '25 01:09

Abdul