这是我在客户端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文件?帮助我提供示例代码。谢谢
答案 0 :(得分:0)
使用Response.End()
后,您可以简单地使用File.Delete()
方法:
System.Web.HttpContext.Current.Response.End();
System.IO.File.Delete(filepath); // add this line
如果您使用FileResult
操作并从流中读取文件,则可以在创建具有指定FileOptions.DeleteOnClose
的FileStream
实例时使用file options overload删除文件:>
[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");
}
或者,您可以创建自定义属性,该属性适用于this reference中提供的FileResult
操作。