我在文件夹中上传文件并在ms sql数据库中保存文件名的路径。我想根据特定记录的sql数据库中保存的路径从该文件夹下载这些文件。我在网上搜索了但是得到的例子是将图像,文件等保存在数据库而不是文件夹中。 如果路径保存在数据库中,请帮助如何从文件夹下载文件。
//Upload files
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("upload/" + FileName));
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into tblFiles (Name, FilePath)" +
" values(@FileName, @FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.AddWithValue("@FilePath", "upload/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
// show data in grid
public void shofile2()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["conString"].ConnectionString;
string strQuery = "select * from tblFiles where UnqId = '" + UnqId1.Text + "'";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
// just trying for download
protected void DownloadFile(object sender, EventArgs e)
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblFiles", con);
SqlDataReader DR1 = cmd.ExecuteReader();
if (DR1.Read())
{
//Label40.Visible = true;
//Label40.Text = DR1.GetValue(5).ToString();
string filePath = DR1.GetValue(2).ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
}
}
//表
CREATE TABLE dbo . tblFiles (
id int IDENTITY(8184,1) NOT NULL,
Name varchar (500) NULL,
FilePath varchar (500) NULL,
ContentType varchar (500) NULL,
Data varbinary (max) NULL,
UnqId int NULL,
remarks varchar (500) NULL,
CONSTRAINT PK_tblFiles PRIMARY KEY CLUSTERED
(
id ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY
) ON PRIMARY TEXTIMAGE_ON PRIMARY
GO
ALTER TABLE dbo . tblFiles WITH CHECK ADD FOREIGN KEY( UnqId )
REFERENCES dbo . pmsbl ( UnqId )
GO
答案 0 :(得分:0)
可以尝试通过更改Response.TransmitFile(Server.MapPath(filePath));与
Response.WriteFile(Server.MapPath(filePath));