Download the file that's returned from the Web Api Post method React

Viewed 626

I have an ASP.Net Web API method which is returning a zip file, which seems happening properly, now what I want is, I want to download that zip file at the client location using React. My Api method is as follows:

        [HttpPost]
    public FileContentResult Post([FromForm] string communityName, [FromForm] string files)
    {          
        var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
        var tFiles = removedInvalidCharsFromFileName.Split(',');
        string rootPath = Configuration.GetValue<string>("ROOT_PATH");
        string communityPath = rootPath + "\\" + communityName;

        byte[] theZipFile = 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();
        }

        return File(theZipFile, "application/zip", communityName + ".zip");
    }

And my React/JS method is as follows:

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

    var formData = new FormData();
    formData.append('communityname', this.state.selectedCommunity);
    formData.append('files', JSON.stringify(this.state['checkedFiles']));

    let env = 'filesApi.' + clientConfiguration['Environment'];        
    let url = clientConfiguration['filesApi.local'];
    alert(url);

    axios({
        method: 'post',
        url: url,
        data: formData
    })
        .then(res => {
            //console.log(res.data);                
            var binaryData = [];
            binaryData.push(res.data);
            const src = window.URL.createObjectURL(new Blob(binaryData, { type: "application/zip" }));

            var fileName = `${this.state['selectedCommunity']}.zip`;
            saveAs(src, fileName);
        });
};

It is downloading the zip file, but says the following error when I try to unzip the file at the client location, what am I missing - not able to understand:

Can not open the file as zip archive, is not archiving, Warning Headers error

, any help please

0 Answers
Related