2016-11-09 135 views
-4

我有一个asp.net webform应用程序(音乐网站)。 我想要一个下载按钮。所以当用户点击。所选音乐开始使用浏览器下载。我该怎么做?如何生成在asp.net c#中下载音乐(mp3)的代码?

这里是我试过的代码:

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(); 

see this picture

+0

你有没有试过做任何事情? –

+0

是的我已经写了一个代码,但音乐保存。文件格式不是.mp3 我写我的代码问题 –

+0

您正在做的test2子字符串是从文件名中修剪.mp3。如果是这样那么这是你的问题。传递给内容处置的文件名部分的值是您将在浏览器中看到的值。如果没有扩展名,它会以.file的形式下载。 – ThatChris

回答

0

试试这个,你可能会得到一个想法

protected void Button1_Click(object sender, EventArgs e) 
    { 

     Response.ContentType = "Application/mp3"; 
     Response.AppendHeader("Content-Disposition", "attachment;filename=filename.mp3"); 
     Response.TransmitFile(Server.MapPath("~\Location\filename.mp3")); 
     Response.End(); 
    } 
+0

我试过这个代码它工作,但下载后音乐有.file格式不.mp3! –

1

试试这个:

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 [email protected]"; 
     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(); 

如果你没有使用数据库然后试试这个:

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."); 
    } 
} 
+0

在数据库中,我有一个音乐表,列是ID,音乐名称,歌手,DatePublish,路径(音乐保存在路径中的例如:../music/musicname.mp3)我没有数据列。 –