• 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();
     

    }

  • 相关阅读:
    orm添加表记录
    创建多表模型
    包的使用
    日志写法
    os模块,是通过和操作系统交互进行操作
    sys python解释器做交互
    软件开发规范
    模块 time模块 datatime模块 random模块
    装饰器
    装饰器进阶
  • 原文地址:https://www.cnblogs.com/ruiying/p/FileToDB.html
Copyright © 2020-2023  润新知