检测文件是否已在ASP.NET MVC 5中成功下载

时间:2018-03-24 21:27:04

标签: c# asp.net-mvc

我的ActionResultStreamContent中提供了HttpResponseMessage result.Content个文件。现在我想跟踪下载的状态,在下载后立即删除文件。

我找到了使用ByteStream的解决方案,它将文件拆分为块,但是如果某些授权测试拒绝请求,则无法提供HttpStatusCode和其他信息。

这是我目前的控制人员:

    [HttpGet]
    public HttpResponseMessage GetZipDownload(string token, string guid)
    {

        if (!dOps.ValidateToken(token))
        {
            return Request.CreateResponse(HttpStatusCode.Unauthorized,
                new HttpError("Unauthorized"));
        }


        Device device = dOps.GetDeviceFromToken(auth);
        AssetOperations assetOps = new AssetOperations();

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

        FileStream file = assetOps.GetZip(guid);
        var content = new StreamContent(file);
        result.Content = content;
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
        result.Content.Headers.Add("Connection", "Keep-Alive");
        result.Content.Headers.Add("Content-Length", (file.Length).ToString());

        return result;
    }

在深入研究ByteStream解决方案之前,我想问一下是否有人可能知道ASP.NET MVC 5的可靠解决方案。

2 个答案:

答案 0 :(得分:1)

您应该从startDownload()创建一个类似:UI thread的方法。 WebClient.DownloadFileAsync()的想法是它会自动为你生成一个工作线程,而不会阻塞调用线程。

作为this thread explainsTrhead将帮助您控制下载,

private void startDownload()
{
    Thread thread = new Thread(() => {
          WebClient client = new WebClient();
          client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
          client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
          client.DownloadFileAsync(new Uri("http://joshua-ferrara.com/luahelper/lua.syn"), @"C:\LUAHelper\Syntax Files\lua.syn");
    });
    thread.Start();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    this.BeginInvoke((MethodInvoker) delegate {
          var bytesReceived = e.BytesReceived;
        //double bytesIn = double.Parse(e.BytesReceived.ToString());
        //double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        //double percentage = bytesIn / totalBytes * 100;
        //label2.Text = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive;
        //progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString()); // YOU CAN HAVE CONTROL OF THE PERCENTAGE OF THE DOWNLOAD, BUT, FOR MVC MAYBE IS BETTER NOT USE IT
    });
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    this.BeginInvoke((MethodInvoker) delegate {
         //TODO: EXECUTE AN EVENT HERE, **THE DOWNLOAD ALREADY IS COMPLETED**!!!
    }); 
}

答案 1 :(得分:1)

您可以注册EndRequest事件处理程序来实现它。

  1. 覆盖MvcApplication类中的Init()方法,并注册到EndRequest事件处理程序。
  2. 使用常量键保存到HttpContext.Current.Items文件路径。
  3. Global.asax文件

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // some startup code, removed for clearity
        }
    
        public override void Init()
        {
            base.Init();
            EndRequest += MvcApplication_EndRequest;
        }
    
        private void MvcApplication_EndRequest(object sender, EventArgs e)
        {
            if (
                HttpContext.Current.Request.Url.AbsolutePath == "/DownloadFileEndedWebsite/Home/Contact" // This should be adjusted.
                && HttpContext.Current.Items.Contains("DownloadFilePath"))
            {
                var filePath = HttpContext.Current.Items["DownloadFilePath"];
                // Delete file here..
            }
        }
    }
    

    <强> HomeController.cs

    public ActionResult Contact()
    {
        HttpContext.Items.Add("DownloadFilePath", "DownloadFilePathValue");
        return View();
    }