如何在asp.net c#中生成下载音乐(mp3)的代码? [英] how to generate code for download a music (mp3) in asp.net c#?
本文介绍了如何在asp.net c#中生成下载音乐(mp3)的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 asp.net 网络表单应用程序(音乐网站).我想要一个下载按钮.所以当用户点击它时.选择的音乐开始使用浏览器下载.我该怎么做?
I have a asp.net webform application (music website). I want to have a download button. So when users clicked on that. selected music start to download with browser.How can I do that?
这是我试过的代码:
string id_new;
id_new = Session["selectedmusicID"].ToString();
DataTable dt2 = new DataTable();
dt2 = blm.selectMusic("sel_music", Convert.ToInt32(id_new));
string test = dt2.Rows[0][9].ToString();
string test2 = test.Substring(9);
Context.Response.Clear();
Context.Response.Buffer = true;
Context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + test2);
Context.Response.ContentType = "audio/mp3";
Context.Response.TransmitFile(@"~\music\" + test2 );
Context.Response.End();
推荐答案
试试这个:
int id = int.Parse(context.Request.QueryString["id"]);
byte[] bytes;
string contentType;
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string name;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
name = sdr["Name"].ToString();
con.Close();
}
}
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
context.Response.ContentType = contentType;
context.Response.BinaryWrite(bytes);
context.Response.End();
如果您不使用数据库,请尝试以下操作:
If you're not using database then try this:
string FileName = dateTimeStamp + "SiteReservation.doc";
if (FileName != "")
{
System.IO.FileInfo file = new System.IO.FileInfo(path + dateTimeStamp + "SiteReservation.doc");
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=SiteReservation.doc");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
//Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
Response.Write("This file does not exist.");
}
}
这篇关于如何在asp.net c#中生成下载音乐(mp3)的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文