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

标签 c# asp.net-core

我已经设置了一个服务器端点,它将压缩一个文件夹并返回压缩文件。在客户端,我有调用端点并将下载的 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/

相关文章:

c# - 目录不存在 - 参数名称 : directoryVirtualPath

c# - 如何在 C# 中使用 SendMessageTimeout 获取窗口标题

c# - .Net Core 2.0 在 dotnet 恢复期间警告 NU1603,NuGet 包出现问题

c# - ASP.NET MVC 6 文件夹授权

c# - 我如何防止使用 C# 进行屏幕录制

c# - 如何在 Windows 8/8.1 中显示 "Set program associations"窗口?

asp.net - 如何在asp.net vnext中使用 Protocol Buffer ?

asp.net - 无法从传输连接读取数据: Operation canceled

c# - 我可以使用反射更改 C# 中的私有(private)只读字段吗?

c# - IEnumerable 的验证(字符串集合)