2016-11-09 139 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)我沒有數據列。 –