下面的代码用于在 Linux 的 Apache Mono MVC2 Web 应用程序中从浏览器保存 PostgreSql 数据库备份。
在文件传输开始之前完成备份需要很长时间。pg_dump 可以写入标准输出而不是文件。如何强制控制器将标准输出通过管道传输到浏览器而不创建临时文件?或者如何向用户显示一些进度指示器?
[Authorize]
public class BackupController : ControllerBase
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Backup()
{
var pinfo = new ProcessStartInfo();
var fn = "temp.backup";
pinfo.Arguments = " -f \"" + fn + "\" -Fc -h \"" + "myserver" + "\" -U \"" + "postgres" + " \"" + "mydb" + "\"";
pinfo.FileName = "/usr/lib/pgsql/pg_dump";
pinfo.UseShellExecute = false;
using (var process = new Process())
{
process.EnableRaisingEvents = true;
process.StartInfo = pinfo;
process.Start();
while (!process.HasExited)
Thread.Sleep(2000);
process.WaitForExit();
if (process.ExitCode!=0)
throw new Exception("error");
process.Close();
}
Response.ClearContent();
Response.WriteFile(fn);
Response.End();
System.IO.File.Delete(fn);
return null;
}
}
更新
我根据答案尝试了下面的代码。从浏览器保存的备份副本会导致 pg_restore 崩溃。如何使用二进制写入或其他东西来创建正确的备份?只有在 pg_dump 完成后浏览器才会提示保存。如果 pd_dump 正在工作,如何实现管道以便通过 Internet 传输数据?
[Authorize]
public class BackupController : ControllerBase
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Backup()
{
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment; filename=\"backup.backup\"");
Response.ContentType = "application/backup";
using (var process = new Process())
{
process.StartInfo.Arguments = " -ib -Z6 -Fc -h \"server\"";
process.StartInfo.FileName = "/usr/lib/pgsql/pg_dump";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
Server.ScriptTimeout = 86400;
process.Start();
while (!process.HasExited)
{
var b = process.StandardOutput.ReadToEnd();
Response.Write(b);
Thread.Sleep(2000);
}
process.WaitForExit();
if (process.ExitCode != 0)
{
return new ContentResult()
{
Content = "Error " + process.ExitCode.ToString()
};
}
var b2 = process.StandardOutput.ReadToEnd();
Response.Write(b2);
process.Close();
Response.End();
return null;
}
}