zoukankan      html  css  js  c++  java
  • 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();
     

    }

  • 相关阅读:
    CentOS 6.4 利用 Awstats 7.2 分析 Nginx 日志
    CentOS 6.4 x64 postfix + dovecot + 虚拟用户认证
    配置日志logwarch 每天发送到邮箱
    CentOSx64 安装 Gearmand 和 Gearman php扩展
    Redis之基本介绍
    Synchronized锁的基本介绍
    Lock的基本介绍
    java之threadlocal的使用
    Java之事务的基本应用
    linux之cp和scp的使用
  • 原文地址:https://www.cnblogs.com/ruiying/p/FileToDB.html
Copyright © 2011-2022 走看看