簡體   English   中英

無法從我的服務器下載 zip 文件

[英]Trouble downloading a zip file from my server

我已經設置了一個服務器端點,它將壓縮文件文件夾並返回 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);
            }
        }
    }

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

返回文件(文件字節,“應用程序/zip”,文件名);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM