zoukankan      html  css  js  c++  java
  • ASP.NET实现写入和读取图片(C#+SQL Server)

    //写入图片到数据库中
      private void WriteImage()
      {
       SqlCommand comm = conn.CreateCommand();
       comm.CommandText = "insert into images(image,type) values(@image,@type)";
       comm.CommandType = CommandType.Text;
       SqlParameter param = comm.Parameters.Add("@image",SqlDbType.Image);
       param.Value = ReadFile();
       param = comm.Parameters.Add("@type",SqlDbType.NVarChar);
       param.Value = GetContentType(new FileInfo(fileName).Extension.Remove(0,1));
       if(comm.executenonquery() == 1)
        Response.Write("Successful");
       else
        Response.Write("Fail");
       
       conn.Close();
      }

      //从数据库中读取图片
      private void ReadImage()
      {
       SqlCommand comm = conn.CreateCommand();
       comm.CommandText = "select image,type from images";
       comm.CommandType = CommandType.Text;
       sqldatareader reader = comm.ExecuteReader();
       while(reader.Read())
       {
        Response.ContentType = reader["type"].ToString();//读写类型  一定要设置 否则浏览器会当作文本输出
        Response.BinaryWrite((byte[])reader["image"]);//图片数据
       }
       response.write("successful");
       Response.End();
       conn.close();
      }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    //其他自定义方法如下:

      //连接数据库
      private void ConnectDB()
      {
       string connStr = "Initial Catalog=;Data Source=;User ID=sa;Password=;";
       conn = new SqlConnection(connStr);
       conn.Open();
      }

    //得到文件名
      private string GetFile()
      {
       HttpPostedFile file = File1.PostedFile;
       fileName = file.FileName;
       return fileName;
      }
      //读取文件内容
      private byte[] ReadFile()
      {
       FileStream file = File.OpenRead(GetFile());
       byte[] content = new byte[file.Length];
       file.Read(content,0,content.Length);
       file.Close();
       return content;
      }

      //获取图片的后缀名
      private string GetContentType(string extension)
      {
       string type = "";
       if(extension.equals("jpg") || extension.Equals("JPG"))
        type = "jpeg";
       else
        type = extension;
       return "image/"+type;
      }

  • 相关阅读:
    vue-常用指令汇总
    vue-插槽和具名插槽
    vue-传值校验
    vue-动态组件
    vue-组件
    zend studio 快捷键收集
    php调试工具firephp
    zend studio插件
    MySQL各个版本区别
    PHP 中 Date 函数与实际时间相差8小时的解决方法
  • 原文地址:https://www.cnblogs.com/top5/p/1625061.html
Copyright © 2011-2022 走看看