无法从我的服务器下载zip文件

时间:2019-08-27 18:58:46

标签: c# asp.net-core

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

1 个答案:

答案 0 :(得分:1)

代替返回Ok(zipFile),只需返回文件即可:

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