FileUpLoad-用法(二)-------上传文件到服务器的数据库

界面主要代码:

<asp:FileUpload ID="FileUpLoad1" runat="server" width="380px"/>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传文件到数据库"/>

后台主要代码实现

protected void Button1_Click(object sender,EventArgs e)

{

    SaveFile();

}

/***********************************************

*本来应使用三层架构实现,为复习以前的知识,这里一起实现

***********************************************/

private void SaveFile()

{

  //得到文件大小

  int fileLength=this.FileUpload1.PostedFile.ContentLength;

  //得到提交的文件

  Stream fileDataStream=this.FileUPload1.PostedFile.InputStreaam;

  //创建数据

  byte[] fileData=new Byte[fileLength];

  //把文件流填充到数组

  fileDataStream.Read(fileData,0,fileLength);

  //得到文件名

  String fileName=this.FileUpload1.FilelName;

  //得到文件类型

   string fileType=this.FileUpload1.PostedFile.ContentType;

 

  //============数据库操作=============================

  //================================================

   string conStr=ConfigurationManager.CoonnectionString[ConStr"].toString();

  SqlConnection con=new SqlConnection(conStr);

    //构建数据库连接,SQL语句,创建参数

  SqlCommand cmd=new SqlCommand("insert into fileData(id,fileName,fileContent,fileType")"+

  Values(@userName,@MyFileName,@MyFile,@FileType)",con);

 

  SqlParamter paramUser=new SqlParamter("@username",SqlDbType.VarChar,30);

    paramUser.Value = Guid.NewGuid().ToString();

  command.Parameters.Add(paramUser);

  SqlParameter paramTitle = new SqlParameter("@MyFileName", SqlDbType.VarChar, 50);

  paramTitle.Value = fileTitle;

  command.Parameters.Add(paramTitle);

  //设置文件内容

  SqlParameter paramData = new SqlParameter("@MyFile", SqlDbType.Image);

  paramData.Value = fileData;

  command.Parameters.Add(paramData);

  SqlParameter paramType = new SqlParameter("@FileType", SqlDbType.VarChar, 30);

  paramType.Value = fileType;

  command.Parameters.Add(paramType);

  //打开连接,执行查询

  connection.Open();
  int result=command.ExecuteNonQuery();

  if(result>0)

  Response.Write("上传成功!");

  connection.Close();
 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/ruiying/archive/2012/05/20/FileToDB.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值