[英]download pdf file at client pc and remove pdf file from server side folder after download begin
这是我在客户端PC上下载pdf的示例代码
$("#btndownload").click(function () {
window.location = '@Url.Action("GeneratePDF", "TestModal")';
return false;
});
public void GeneratePDF()
{
bool IsPdfGenerated = false;
List<Student> studentsVM = new List<Student>
{
new Student {ID=1,FirstName="Joy", LastName="Roy", FavouriteGames="Hocky"},
new Student {ID=2,FirstName="Raja", LastName="Basu", FavouriteGames="Cricket"},
new Student {ID=3,FirstName="Arijit", LastName="Banerjee",FavouriteGames="Foot Ball"},
new Student {ID=4,FirstName="Dibyendu", LastName="Saha", FavouriteGames="Tennis"},
new Student {ID=5,FirstName="Sanjeeb", LastName="Das", FavouriteGames="Hocky"},
};
var viewToString = StringUtilities.RenderViewToString(ControllerContext, "~/Views/Shared/_Report.cshtml", studentsVM, true);
string filepath = HttpContext.Server.MapPath("~/PDFArchives/") + "mypdf.pdf";
Document pdfDoc = null;
try
{
StringReader sr = new StringReader(viewToString);
pdfDoc = new Document(PageSize.A4, 10f, 10f, 30f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(filepath, FileMode.Create));
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
IsPdfGenerated = true;
}
catch (Exception ex)
{
IsPdfGenerated = false;
}
System.Web.HttpContext.Current.Response.ContentType = "pdf/application";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;" +
"filename=sample101.pdf");
System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
System.Web.HttpContext.Current.Response.Write(pdfDoc);
System.Web.HttpContext.Current.Response.End();
}
我知道存储在filepath中的pdf文件路径。 下载开始后,如何在服务器端删除pdf文件? 帮助我提供示例代码。 谢谢
您可以在使用Response.End()
之后简单地使用File.Delete()
方法:
System.Web.HttpContext.Current.Response.End();
System.IO.File.Delete(filepath); // add this line
如果使用FileResult
操作并从流中读取文件,则可以在创建具有指定文件选项重载的 FileStream
实例时使用FileOptions.DeleteOnClose
删除文件:
[HttpGet]
public FileResult GeneratePDF()
{
// other stuff
string filepath = HttpContext.Server.MapPath("~/PDFArchives/") + "mypdf.pdf";
// other stuff
var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
return File(stream, "application/pdf", "sample101.pdf");
}
或者,您可以创建自定义属性,该属性适用于本参考中提供的FileResult
操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.