下载从Web Api Post方法React返回的文件

时间:2019-10-15 01:09:32

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

我有一个ASP.Net Web API方法,该方法返回一个zip文件,该文件似乎正常发生,现在我想要的是,我想使用React在客户端位置下载该zip文件。我的Api方法如下:

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

我的React / JS方法如下:

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

它正在下载zip文件,但是当我尝试在客户端位置解压缩文件时出现以下错误,我缺少什么-无法理解:

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

,有什么帮助

0 个答案:

没有答案