二進制流上傳圖片,預覽,讀取顯示


上傳圖片並生成縮略圖預覽效果

<div>
  <asp:FileUpload ID="FileUpload1" runat="server" CssClass="btn" Width="320px" onchange="getValue()" />&nbsp;<asp:Button ID="btnAdd" runat="server" Text="Submit" ValidationGroup="AddPlat" CssClass="btn" Width="80px" OnClick="btnAdd_Click" />
  <div id="t2" runat="server" style="width: 150px; height: 120px; visibility: hidden; display: none; border: solid 1px #CCC;">
      <img alt="" id="t1" runat="server" src="" style="width: 150px; height: 120px; border: solid 1px #CCC; display: none;" />
  </div>
  <asp:Image ID="imageSony" runat="server" BorderStyle="Solid" Width="150px" Height="120px" ImageUrl="" />
</
div>

getvalue() Function的定義在一下Javascript中:

Javascript
    <script type="text/javascript">
function getValue(){ 

    var isIE = (document.all) ? true : false;
    var isIE7 = isIE && (navigator.userAgent.indexOf('MSIE 7.0') != -1);
    var isIE8 = isIE && (navigator.userAgent.indexOf('MSIE 8.0') != -1);
    var isMozilla = /mozilla/.test( navigator.userAgent ) && !/(compatible|webkit)/.test( navigator.userAgent )
    var isOpera = /Opera/.test( navigator.userAgent )

    var t1=document.getElementById("t1")
    var t2=document.getElementById("t2")
    var imgsony=document.getElementById("imageSony")
    var t=document.getElementById("FileUpload1");
    var value=t.value
    
    t1.style.display="block";
    t2.style.display="block";
    imgsony.style.display="none";
    
    if(isIE7 || isIE8){
        t.select();
        var value=document.selection.createRange().text;
        document.selection.empty();
    }else if(isMozilla){
        value = t.files[0].getAsDataURL();
    }
    
    //alert(value)
    
    
    if(isIE7 || isIE8){
        t1.style.visibility="hidden"
        //t1.style.display="none";
        t2.style.visibility=""
        
        t1.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image')"
        t1.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale')"
    
        t2.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image')"
        t2.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale')"
    
        t1.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=value;
        
        t2.style.width=t1.offsetWidth
        t2.style.height=t1.offsetHeight
    
        t2.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=value;
    }else{
        t1.src=value
    }
}

    </script>


二進制流方式存入數據庫

string fullFileName = FileUpload1.PostedFile.FileName;
//string fileName = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);//圖片名稱
string type = fullFileName.Substring(fullFileName.LastIndexOf(".") + 1).ToLower();
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png" || type == "jpeg")
{
      HttpPostedFile upFile = FileUpload1.PostedFile;//HttpPostedFile對象,用來讀取上傳圖片的屬性
     int fileLength = upFile.ContentLength;//記錄文件的長度
     byte[] fileBytePicture = new byte[fileLength];//用圖片的長度來初始化一個字節數組存儲臨時的圖片文件
     Stream fileStream = upFile.InputStream;//建立文件流對象
     fileStream.Read(fileBytePicture, 0, fileLength);
      //Insert into db, picture字段,image類型
      //在此要注意,SQL語句中插入DB不能像varchar()類型,用單引號引起來,這樣的話會報錯,要使用參數自行插入,eg:
      //cmd.CommandText = @"INSERT INTO Category(Category,Picture)VALUES(@Category,@Picture)";
     //cmd.Parameters.AddWithValue("@Category", category);//string category
//cmd.Parameters.AddWithValue("@Picture", picture);
// byte[] picture }

其中,Stream fileStream = upFile.InputStream;//建立文件流對象
        fileStream.Read(fileBytePicture, 0, fileLength);
建立文件流對象,生成二進制流必須存在,不能去掉,否則能夠生成二進制流保存到數據庫中。 

 

從數據庫讀取圖片

 

BindItem();

 imageSony.ImageUrl = "ReadImage.aspx?itemid=" + itemID;

ReadImage.aspx.cs

ReadImage。aspx.cs
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string imageid = "1";
                if (Request.QueryString["itemid"] != null)
                {
                    imageid = Request.QueryString["itemid"].ToString();
                }
                int imgID = Int32.Parse(imageid);
                ShowImage(imgID);
            }
        }

        private void ShowImage(int itemID)
        {
            DataTable dt = new DataTable();
            dt = srb.GetSonyItem(itemID);//獲得數據源
            byte[] b_image = (byte[])dt.Rows[0]["Picture"];//得到數據庫二進制字段內容
            if (b_image.Length > 0)
            {
                Byte[] byteImg = (byte[])dt.Rows[0]["Picture"];
                Response.BinaryWrite(byteImg);//寫入二進制流
                Response.End();
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM