將圖片保存到數據庫中並下載[原]

這個功能是我們常用的,但我發現網上參考資料好像並不多,有也不夠全.我想我能寫全一點吧?供我們的程序員提供一個方便.

首先我們要建立一個數據庫和表:
1. --創建存儲圖片的數據庫

CREATE DATABASE [Tom_Hu] ON (NAME = N'Tom_Hu_Data', FILENAME = N'd:Program FilesMicrosoft SQL ServerMSSQLdataTom_Hu_Data.MDF' , SIZE = 1, FILEGROWTH = 10%LOG ON (NAME = N'Tom_Hu_Log', FILENAME = N'd:Program FilesMicrosoft SQL ServerMSSQLdataTom_Hu_Log.LDF' , SIZE = 1, FILEGROWTH = 10%)
COLLATE Chinese_PRC_CI_AS
GO

       2. --建立一個存儲圖片的表 

   CREATE TABLE [Images] (
[id] [int] IDENTITY (11NOT NULL ,
[ImageName] [varchar] (64) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Images] [image] NOT NULL ,
[ImageSize] [int] NULL 
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO 

3.建立一個名爲 ImageTest 的asp.net網站

4.在Default.aspx文件中加入以下代碼:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>關於圖片上傳和下載的測試</title>
    
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body style="text-align: left">
    
<form id="form1" runat="server">
    
<div>
        
<table style="border-right: #3333ff thin solid; border-top: #3333ff thin solid; border-left: #3333ff thin solid; border-bottom: #3333ff thin solid;">
            
<tr>
                
<td colspan="2">
                    
<asp:FileUpload ID="UpFileControl" runat="server" /></td>
            
</tr>
            
<tr>
                
<td style="text-align: center">
                    
<asp:Button ID="BT_UpFile" runat="server" Text="上傳" OnClick="BT_UpFile_Click" /></td>
                
<td style="text-align: center">
                    
<asp:Button ID="BT_Down" runat="server" Text="下載" OnClick="BT_Down_Click" /></td>
            
</tr>
        
</table>
    
</div>
    
</form>
</body>
</html>

 

5.在配置文件Web.config中寫入:

<?xml version="1.0"?>
<!-- 
    注意: 除了手動編輯此文件以外,您還可以使用 
    Web 管理工具來配置應用程序的設置。可以使用 Visual Studio 中的
     “網站”->“Asp.Net 配置”選項。
    設置和註釋的完整列表在 
    machine.config.comments 中,該文件通常位於 
    WindowsMicrosoft.NetFrameworkv2.xConfig 中
-->
<configuration>
<appSettings/>
<connectionStrings>
   
<add name="databasecon" connectionString="Data Source=.;Initial Catalog=Tom_Hu;Persist Security Info=True;User ID=sa;Password=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
   
<!-- 
            設置 compilation debug="true" 將調試符號插入
            已編譯的頁面中。但由於這會 
            影響性能,因此只在開發過程中將此值 
            設置爲 true。
        
-->
   
<compilation debug="true"/>
   
<!--
            通過 <authentication> 節可以配置 ASP.NET 使用的 
            安全身份驗證模式,
            以標識傳入的用戶。 
        
-->
   
<authentication mode="Windows"/>
   
<!--
            如果在執行請求的過程中出現未處理的錯誤,
            則通過 <customErrors> 節可以配置相應的處理步驟。具體說來,
            開發人員通過該節可以配置
            要顯示的 html 錯誤頁
            以代替錯誤堆棧跟蹤。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        
-->
</system.web>
</configuration>


6.在Default.aspx.cs文件中寫上:

 

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;


/// <summary>
/// 作者:三少爺
/// 日期:2007-11-14
/// </summary>

public partial class _Default : System.Web.UI.Page 
{
    
protected int imageSize;
    
protected byte[] imageBody;
    
protected string SqlCom = "";
    SqlConnection con 
= new SqlConnection();
    SqlCommand cmd 
= new SqlCommand();

    
protected void Page_Load(object sender, EventArgs e)
    
{
        
//創建數據庫鏈接對象
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["databasecon"].ToString());
    }


    
//圖片上傳
    protected void BT_UpFile_Click(object sender, EventArgs e)
    
{
        
string imagePath;
        
string imageType;
        
string imageName;
        
if (UpFileControl.PostedFile.FileName != "")
        

            
//取得選擇的圖片路徑
            imagePath = UpFileControl.PostedFile.FileName;
            
//取得選擇的圖片擴展名
            imageType = imagePath.Substring(imagePath.LastIndexOf("."+ 1);
            
//取得選擇的圖片名
            imageName = imagePath.Substring(imagePath.LastIndexOf("/"+ 1);

            
if ("jpg" != imageType && "gif" != imageType)
            
{
                Response.Write(
"對不起!請您選擇JPG或者GIF格式的圖片!");
                
return;
            }

            
else
            

                
//建立訪問客戶端上傳文件的對象
                HttpPostedFile SendImage = UpFileControl.PostedFile;
                
//取得圖片的大小
                imageSize = SendImage.ContentLength;
                imageBody 
= new Byte[imageSize];
                
//建立數據流對象
                Stream StreamObject = SendImage.InputStream;
                
//把圖像數據放到imageBody中,其中0代表數據指針位置,ImageSize代表要讀取的流的長度
                StreamObject.Read(imageBody, 0, imageSize);
                SqlCom 
= "insert into Images(ImageName,Images,ImageSize,imgtype) VALUES(@ImageName,@Images,@ImageSize,@imgtype) ";  // '" + imageName + "','" + imageBody + "','" + imageSize.ToString() + "','" + imageType + "')";
                cmd = new SqlCommand(SqlCom,con);
                cmd.Parameters.AddWithValue(
"@ImageName", imageName);//@Images,@ImageSize,@imgtype
                cmd.Parameters.AddWithValue("@Images", imageBody);
                cmd.Parameters.AddWithValue(
"@ImageSize", imageSize);
                cmd.Parameters.AddWithValue(
"@imgtype", imageType);
                con.Open();
                
try
                
{
                    cmd.ExecuteNonQuery();
                    Response.Write(
"成功!");
                }

                
catch
                
{
                    Response.Write(
"失敗!");
                }

                
finally
                
{
                    con.Close();
                }

            }

        }

    }


    
//圖片下載
    protected void BT_Down_Click(object sender, EventArgs e)
    
{
        SqlCom 
= "select top 1 * from images order by id desc";
        cmd 
= new SqlCommand(SqlCom, con);
        con.Open();
        SqlDataReader myreader 
= cmd.ExecuteReader();
        myreader.Read();
        
//設置頁面緩衝輸出
        Response.Buffer = true;
        
//清除緩衝區中的所有內容
        Response.Clear();
        
//設置輸出流的類型
        Response.ContentType = "gif";
        
//爲輸出流添加HTTP頭信息,在這裏用圖片的名稱作爲下載的文件名稱
        Response.AddHeader("Content-Disposition""attachment;filename=" +HttpUtility.UrlEncode( myreader["imagename"].ToString(), System.Text.Encoding.GetEncoding("UTF-8")) +";");

        
byte[] file = (byte[])myreader["images"];
        
//把二進制字符串寫入HTTP輸出流
        Response.Write(file);
        
//向客戶端發送所有緩衝的內容
        Response.Flush();
        
////將當前所有緩衝的輸出發送到客戶端,並停止該頁的執行
        Response.End();
        con.Close();
        myreader.Close();
    }


    
protected void Button1_Click(object sender, EventArgs e)
    
{
        Image1.ImageUrl 
= "ShowImg.aspx";
    }

}

 

也許我寫得很麻煩很囉嗦,但我相信這對初學者是有用的.
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章