我正在编写一个小型 Web 应用程序,部分功能是能够将日志从服务器下载到用户的文件系统。我能够压缩现有日志,但无法让压缩文件夹传输。我在这里浏览了许多其他类似的问题,但还没有根据其中任何一个问题来解决这个问题。
这是我目前正在尝试的代码:
.Net 控制器
[HttpPost]
public ActionResult DownloadLogs()
{
string path = System.Configuration.ConfigurationManager.AppSettings["LogPath"];
try
{
Log.Information("Closing current logger. AudtiLog: {auditLog}", true);
Log.CloseAndFlush();
string startPath = path;
string zipPath = "C:\\my_folder\\result.zip";
string extractPath = path + "extract";
//deleting existing zips
if (System.IO.File.Exists(zipPath))
System.IO.File.Delete(zipPath);
if (System.IO.Directory.Exists(extractPath))
System.IO.Directory.Delete(extractPath, true);
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
FileInfo file = new FileInfo(zipPath);
using (FileStream filestream = new FileStream(zipPath, FileMode.Open))
{
return File(filestream, "application/zip", "ServerLogZip.zip");
}
}
catch (Exception ex)
{
Log.Error("Error occurred when downloading server logs. Error: {Error}; AuditLog: {auditLog}", ex.Message, true);
return Json(new { result = "error" });
}
}
Javascript
function DownloadLogs() {
$.ajax({
type: "POST",
url: "/ManageServer/DownloadLogs",
contentType: "application/zip",
success: function (response) {
alert("Success")
},
error: function (response) {
alert("Error");
}
});
}
每当我运行它时,它都会将日志压缩到一个文件夹中,Response
成功地逐步完成部分代码,但没有任何反应。我已经尝试调试并单步执行代码,但还没有找到答案。我也试过这个Response.WriteFile
方法。没运气。
编辑
我已经更新了要返回的代码ActionResult
并返回了一个File
. 它当前从服务器返回 500 错误。