简体   繁体   中英

Trouble downloading a zip file from my server

I've set up a server endpoint that will zip a folder of files and return the zip file. On the client-side, I have code that calls the endpoint and saves the downloaded zip file to disk. All the code runs, but the resultant file is bigger than the zip file on the server and if I try to open the resultant zip file, I get "Windows can't open the file, file is invalid". What am I doing wrong?

Server code:

    [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);
    }

Client code:

    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);
            }
        }
    }

Instead of returning the Ok(zipFile), just return the file:

return File(fileBytes, "application/zip", fileName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM