gpt4 book ai didi

c# - 从我的服务器下载 zip 文件时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:31 25 4
gpt4 key购买 nike

我已经设置了一个服务器端点,它将压缩一个文件夹并返回压缩文件。在客户端,我有调用端点并将下载的 zip 文件保存到磁盘的代码。所有代码都运行,但生成的文件比服务器上的 zip 文件大,如果我尝试打开生成的 zip 文件,我会得到“Windows 无法打开文件,文件无效”。我做错了什么?

服务器代码:

    [Route("projects/files/download")]
[HttpPost]
public ActionResult Post([FromForm] DownloadFileRequest request)
{
string filesPath = ...;
string zipName = ...;
if (!Directory.Exists(filesPath)) {`
return BadRequest("File path not found on server");
}
if (System.IO.File.Exists(zipName)) System.IO.File.Delete(zipName);
System.IO.Compression.ZipFile.CreateFromDirectory(filesPath, zipName);
byte[] fileBytes = System.IO.File.ReadAllBytes(zipName);
FileContentResult zipFile = File(fileBytes, "application/zip", fileName);
return Ok(zipFile);
}

客户端代码:

    Uri uri = new Uri("https://.../projects/files/download");
response = client.PostAsync(uri.ToString(), formContent).Result;
if (response.IsSuccessStatusCode)`
{
using (HttpContent content = response.Content)
{
Stream stream = content.ReadAsStreamAsync().Result;
string path = ...;
stream.Seek(0, SeekOrigin.Begin);
using (Stream streamToWriteTo = File.Open(path, FileMode.Create))
{
stream.CopyTo(streamToWriteTo);
}
}
}

最佳答案

不返回 Ok(zipFile),只返回文件:

返回文件(fileBytes, "application/zip", fileName);

关于c# - 从我的服务器下载 zip 文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57680759/

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