我已经设置了一个服务器端点,它将压缩文件文件夹并返回 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);
}
}
}
潇湘沐
相关分类