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

后端 未结 13 1015
执念已碎
执念已碎 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:45

    overriding the OnResultExecuted method is probably the correct solution.. This method runs after the response is written.

    public class DeleteFileAttribute : ActionFilterAttribute 
    { 
        public override void OnResultExecuted(ResultExecutedContext filterContext) 
        { 
            filterContext.HttpContext.Response.Flush();
            // Delete file 
        } 
    } 
    

    Action code:

    [DeleteFileAttribute]
    public FileContentResult GetFile(int id)
    {
       //your action code
    }
    
    0 讨论(0)
  • 2020-12-07 21:50

    You can return just regular FileStreamResult which is opened with FileOptions.DeleteOnClose. File stream will be disposed with result by asp.net. This answer dosen't require usage of low level response methods which may backfire in certain situations. Also no extra work will be done like loading file to memory as whole.

    var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
    return File(
        fileStream: fs,
        contentType: System.Net.Mime.MediaTypeNames.Application.Octet,
        fileDownloadName: "File.abc");
    

    This answer is based on answer by Alan West and comment by Thariq Nugrohotomo.

    0 讨论(0)
  • 2020-12-07 21:52

    Above answers helped me, this is what I ended up with:

    public class DeleteFileAttribute : ActionFilterAttribute
    {
      public override void OnResultExecuted(ResultExecutedContext filterContext)
      {
         filterContext.HttpContext.Response.Flush();
         var filePathResult = filterContext.Result as FilePathResult;
         if (filePathResult != null)
         {
            System.IO.File.Delete(filePathResult.FileName);
         }
      }
    }
    
    0 讨论(0)
  • 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 = "<Full path your file name>"; //Your actual file name
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=<file name to be shown as download>"); //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
    }
    
    0 讨论(0)
  • 2020-12-07 21:54

    Try This. This will work properly.

    public class DeleteFileAttribute : ActionFilterAttribute
    {
      public override void OnResultExecuted( ResultExecutedContext filterContext )
      {
        filterContext.HttpContext.Response.Flush();
        string filePath = ( filterContext.Result as FilePathResult ).FileName;
        File.Delete( filePath );
      }
    }
    
    0 讨论(0)
  • 2020-12-07 21:55

    I performed same action in WebAPI. I needed to delete file just after it downloaded form server. We can create custom response message class. It takes file path as parameter and delete it once its transmitted.

     public class FileHttpResponseMessage : HttpResponseMessage
        {
            private readonly string filePath;
    
            public FileHttpResponseMessage(string filePath)
            {
                this.filePath = filePath;
            }
    
            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
                File.Delete(filePath);
            }
        }
    

    Use this class as below code and it will delete your file once it will be written on response stream.

    var response = new FileHttpResponseMessage(filePath);
                response.StatusCode = HttpStatusCode.OK;
                response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "MyReport.pdf"
                };
                return response;
    
    0 讨论(0)
提交回复
热议问题