开发者

How to Download a Video using ASP.NET?

开发者 https://www.devze.com 2022-12-26 16:46 出处:网络
how to download a vi开发者_Go百科deo file .wmv and save it to the user\'s disk when click a button without using the browser save link as This is not that hard to do.As dtb mentions, the user\'s brows

how to download a vi开发者_Go百科deo file .wmv and save it to the user's disk when click a button without using the browser save link as


This is not that hard to do. As dtb mentions, the user's browser will still ask the user for permission to download the file, and they may have the option of choosing where to save the file. So it will not be completely automatic.

Here is a link to a blog post explaining how this is done using webforms. The main part you are interested in is this:

Response.ContentType = "video/x-ms-wmv";
Response.AppendHeader("Content-Disposition","attachment; filename=MyMovie.wmv");
Response.TransmitFile( Server.MapPath("~/videos/MyMovie.wmv") );
Response.End();

Here is a link stack overflow question which explains how to do it in MVC.

Based on your comment, you want to do this in silverlight. I'm not an expert in silverlight, but here is another question on stack overflow that discusses the issue.


You can use the WebClient to download a wmv file and the SaveFileDialog to ask the user where to put it:-

void DownloadButton_Click(object sender, RoutedEventArgs e)
{
  var dialog = new SaveFileDialog();
  if (dialog.ShowDialog().Value)
  {
    var web = new WebClient();
    web.OpenReadCompleted = (s, args) =>
    {
      try
      {
        using (args.Result)
        using (Stream streamOut = args.UserState As Stream)
        {
          Pump(args.Result, streamOut);
        }
      }
      catch
      {
         // Do something sensible when the download has failed.
      }

    };
    web.OpenReadAsync(UriOfWmv,  ShowDialog.OpenFile()); 
  }
}

private static void Pump(Stream input, Stream output)
{
  byte[] bytes = new byte[4096];
  int n;

  while((n = input.Read(bytes, 0, bytes.Length)) != 0)
  {
    output.Write(bytes, 0, n);
  }
}

However currently there isn't a way to display download progress information. I was hoping that would get into the Silverlight 4 but as far as I can see it hasn't.


Try adding a method in the controller that will help download the video.

[HttpGet]
public FileResult DownloadFile(int? fileId)
{
   FilesEntities entities = new FilesEntities();
   Video video = entities.Videos.ToList().Find(p => p.id == fileId.Value);
   return File(video.Data, video.ContentType, video.Name);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消