Asp.net 文件上载/下载失败
我正在一个网站上工作,我需要有上传/下载功能。上传工作正常,但当我按下下载上传的文件时,几乎什么也没发生Asp.net 文件上载/下载失败,asp.net,Asp.net,我正在一个网站上工作,我需要有上传/下载功能。上传工作正常,但当我按下下载上传的文件时,几乎什么也没发生 //Upload protected void btnUpload_Click(object sender, EventArgs e) { string filename = Path.GetFileName(fileUpload1.PostedFile.FileName); fileUpload1.SaveAs(Server.
//Upload
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/" + filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con);
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@Path", "Files/" + filename);
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
//Download
protected void gvDetails_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand("select FileName,FilePath from FilesTable where Id=@Id", con);
com.Parameters.AddWithValue("Id", gvDetails.SelectedRow.Cells[1].Text);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = dr["type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["data"]);
Response.End();
}
}
您的代码几乎没有问题:
select
查询只返回文件名和文件路径,但您也尝试从数据库中检索类型和数据。您可以在表中添加一个额外的列来存储文件类型,因为您的代码已经将上载的文件保存在文件文件夹中,然后您可以使用dr[“type”]
// Uploading
string filePath = Server.MapPath("Files/" + filename); // Absolute path
or
string filePath = "Files/" + filename; // Relative path
...
cmd.Parameters.AddWithValue("@Path", filePath);
// Downloading
string filePath = dr["FilePath"]; // Absolute path
or
string filePath = Server.MapPath(dr["FilePath"]); // Relative path
file
或FileStream
等将其内容读取为字节以发送到客户端:
// ReadAllBytes throws memory exception for large files
byte[] fileData = File.ReadAllBytes(filePath);
select
列表包含文件名作为列名,而不仅仅是名称,请将dr[“name”]
替换为dr[“FileName”]
你试过突破点吗?“几乎什么都没有”到底是什么意思?@eniaBogdasic:为什么不呢?你有什么例外吗?@radium我想它只是刷新了页面。我只做过代码分析。