ASP.NET Tutorial/ADO.net Database/Image Saving

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Read image from database and send to client

<%@ Page %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<script runat="server" language="C#">
void Page_Load(Object sender, EventArgs e)
{
  string connectionString = "Data Source=myServer;Initial Catalog=myCatalog;User Id=user;Password=pass";
  SqlConnection objConnection = new SqlConnection(connectionString);
  string commandText = "SELECT Image FROM imageTable";
  SqlCommand objCommand = new SqlCommand(commandText, objConnection);
  SqlDataReader objReader = null;
      
  try {
    objConnection.Open();
    objReader = objCommand.ExecuteReader();
    
    if (objReader.Read()) 
    {
      Response.ContentType = "image/jpeg";
      Response.BinaryWrite((Byte[])objReader["Image"]);
    }
  } catch (Exception exc) 
  {
    Response.Write(exc.Message);
    Response.Write("<br>This page would display an image if its connection string were set up.");
  } 
  finally 
  {
    if ((objConnection != null) && (objConnection.State == ConnectionState.Open)) 
    {
      objConnection.Close();
    }
    if (objReader != null)
    objReader.Close();
  }
}
</script>


Save image to database

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void UploadImage(Object sender, EventArgs e)
{
  String connectionString = "Enter your Connection String";
  Stream imageStream = ImageFile.PostedFile.InputStream;
  Byte[] byteData = new Byte[ImageFile.PostedFile.ContentLength];
  SqlConnection objConn = new SqlConnection(connectionString);
  SqlCommand objCommand = new SqlCommand("INSERT INTO sql_images(Image) VALUES(@image)", objConn);
  SqlParameter objParam = new SqlParameter("@image", SqlDbType.Image);
  imgStream.Read(imgdata, 0, ImageFile.PostedFile.ContentLength);
  objParam.Value = imgdata;
  objCommand.Parameters.Add(imgparam);
  try
  {
    objConn.Open();
    objCommand.ExecuteNonQuery();
  } 
  catch (System.Exception exc)
  {
    ErrorLabel.Text = exc.ToString();
  }
  finally
  {
    objConn.Close();
    imgStream.Close();
  }
}
</script>
<form enctype="multipart/form-data" runat="server">
  <input id="imageFile" runat="server" type="file" />
    <asp:button runat="server" OnClick="UploadImage" Text="Upload" />
  <asp:Label id="ErrorLabel" runat="server" />
</form>