How to delete file after download with ASP.NET MVC?

后端 未结 13 1052
执念已碎
执念已碎 2020-12-07 20:51

I want to delete a file immediately after download, how do I do it? I\'ve tried to subclass FilePathResult and override the WriteFile method where

13条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 21:54

    Here is updated answer based on elegant solution by @biesiad for ASP.NET MVC ( https://stackoverflow.com/a/4488411/1726296)

    Basically it returns EmptyResult after response is sent.

    public ActionResult GetFile()
    {
        string theFilename = ""; //Your actual file name
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename="); //optional if you want forced download
            Response.ContentType = "application/octet-stream"; //Appropriate content type based of file type
            Response.WriteFile(theFilename); //Write file to response
            Response.Flush(); //Flush contents
            Response.End(); //Complete the response
            System.IO.File.Delete(theFilename); //Delete your local file
    
            return new EmptyResult(); //return empty action result
    }
    

提交回复
热议问题