gpt4 book ai didi

javascript - 使用 React 从 FileStream 返回下载文件

转载 作者:行者123 更新时间:2023-12-05 02:10:41 25 4
gpt4 key购买 nike

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

最佳答案

最终通过使用 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 给予的所有支持 - 非常感谢。

关于javascript - 使用 React 从 FileStream 返回下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58456588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com