文件上传时,在Form中必须进行如下的设置:
<form id="form1" method="post" encType="multipart/form-data" runat="server">
另外,如果上传的文件大小超过2M时,还要修改web.config的内容以使程序能够正确运行,在<system.web>和</system.web>中加入下面的代码:
<httpRuntime executionTimeout="300" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/>
其中maxRequestLength就是要上传的文件的内容的最大长度.
下面是实现多个文件上传的源代码
protected void btnupload_Click(object sender, EventArgs e)
{
//得到要上传的文件列表
HttpFileCollection upfiles = HttpContext.Current.Request.Files;
for (int i = 0; i < upfiles.Count; i++)
{
if (i < upfiles.Count && i < 10)
{
if (upfiles[i].FileName != String.Empty || upfiles[i] != null)
{
HttpPostedFile file = upfiles[i];
//得到要上传的文件的大小
int Filesize = file.ContentLength;
//下面的方法用来得到文件在客户端的完整路径
string filepathfull = file.FileName.ToString().Trim();
//得到要上传的文件的扩展名
string filenameext = System.IO.Path.GetExtension(file.FileName);
//得到要上传的文件不带扩展名的名称
string filenamewithoutext = System.IO.Path.GetExtension(file.FileName);
//保存要上传的文件,文件的地址要用服务器上的地址.
file.SaveAs(Server.MapPath("文件路径") );
}
}
}
}
下面的代码用来实现把上传的数据保存到数据库中:
private void WriteFileToDB()
{
HttpPostedFile file = upfiles[i];
int Filesize = file.ContentLength;
string filenameext = System.IO.Path.GetExtension(file.FileName);
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "insert into FileTable(file,type) values(@file,@type)";
comm.CommandType = CommandType.Text;
SqlParameter param = comm.Parameters.Add("@file",SqlDbType.Image);
byte [] inputbyte = new byte[file. ContentLength];
file.InputStream.Read(inputbyte, 0, file. ContentLength)
param.Value = inputbyte;
param = comm.Parameters.Add("@type",SqlDbType.NVarChar);
param.Value = System.IO.Path.GetExtension(file.FileName);
if(comm.ExecuteNonQuery() == 1)
Response.Write("Successful");
else
Response.Write("Fail");
conn.Close();
}
下面的实现文件下载的源代码:
if(dr.Read())
{
Context.Response.Buffer = true;
Context.Response.Clear();
Context.Response.ContentType = dr["CContentType"].ToString();
Context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
Context.Response.BinaryWrite((Byte[])dr["CContent"]);
Context.Response.Flush();
Context.Response.End();
}