简体   繁体   English

如何用asp.net下载音乐

[英]how to download music with asp.net

I have an asp.net webform application. 我有一个asp.net Webform应用程序。 I want to have a button for downloading musics, so I write below code block : 我想有一个下载音乐的按钮,所以我在下面的代码块中写:

protected void Button1_Click(object sender, EventArgs e)
{
    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();
    Response.ContentType = "application/mp3";
    Response.AddHeader("Content-Disposition", dt2.Rows[0][9].ToString());
    Response.TransmitFile(Server.MapPath( dt2.Rows[0][9].ToString()));
    Response.End();
}

When I run this code and click on button it downloads the music.aspx page not mp3 file.I don't know what is my mistake. 当我运行此代码并单击按钮时,它会下载music.aspx页面而不是mp3文件。我不知道我的错误是什么。 Anyone can help me? 有人可以帮助我吗?

Finally I've solved my problem, as you can see in the code below... first I create a column named MusicByte to my music table in database.I stored the data of every music by file uploading in this column... 终于我解决了我的问题,正如您在下面的代码中看到的...首先,我在数据库的音乐表中创建了一个名为MusicByte的列。我通过在此列中上传文件来存储每种音乐的数据...

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 filename = test.Substring(9).Replace(" " , "").Replace(".mp3" , ".MP3");
byte[] buffer = (byte[])(dt2.Rows[0][10]);
Response.ContentType = "audio/mpeg";
Response.AddHeader("Content-Disposition", "Attachment;filename=" + filename);
byte[] datablock = new byte[0x1000];
long filesize;
int bytesread;
long totalsbytesread = 0;
using (Stream st = new MemoryStream(buffer))
        {
            filesize = st.Length;
            while (totalsbytesread < filesize)
            {
                if (Response.IsClientConnected)
                {
                    bytesread = st.Read(datablock, 0, datablock.Length);
                    Response.OutputStream.Write(datablock, 0, bytesread);
                    Response.Flush();
                    totalsbytesread += bytesread;
                }
            }
        }
        Response.End();

deleting spaces in filename and replice the .mp3 to .MP3 was usefull.Also this video in you tube helps me : Upload and download files to/from a SQL Server database 删除文件名中的空格并将.mp3改成.MP3是有用的。此外,此视频还可以帮助我:将文件上传到SQL Server数据库或从SQL Server数据库下载文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM