2012-12-12 43 views
0

首先,我想說,是的,我知道有文件系統,這樣做的,只是保存文件名/位置數據庫最好的方式去,我可能會在最終版本中做到這一點。保存一個文件從PHP數據庫,查看它的數據庫在VB.net

這主要是概念/實驗/證明一個學習的機會。

我有一個PHP上傳表單正在工作。它需要一個圖像並將其轉換爲base64字符串,並將其放入數據庫表中的圖像塊中。

<?php 
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
    // cleaning title field 
    $title = trim(sql_safe($_POST['title'])); 

    if ($title == '') // if title is not set 
     $title = '(empty title)';// use (empty title) string 

    if ($_POST['password'] != $password) // cheking passwors 
     $msg = 'Error: wrong upload password'; 
    else 
    { 
     if (isset($_FILES['photo'])) 
     { 
      @list(, , $imtype,) = getimagesize($_FILES['photo']['tmp_name']); 
      // Get image type. 
      // We use @ to omit errors 

      if ($imtype == 3) // cheking image type 
       $ext="png"; // to use it later in HTTP headers 
      elseif ($imtype == 2) 
       $ext="jpeg"; 
      elseif ($imtype == 1) 
       $ext="gif"; 
      else 
       $msg = 'Error: unknown file format'; 

      if (!isset($msg)) // If there was no error 
      { 
      //$file = File Image yang ingin di encode 
      //Filetype: JPEG,PNG,GIF 
      $base64 = ""; 
      $file = $_FILES['photo']['tmp_name']; 
      if($fp = fopen($file,"rb", 0)) 
      { 
       $gambar = fread($fp,filesize($file)); 
       fclose($fp); 
       $base64 = chunk_split(base64_encode($gambar)); 
      }  
       // Preparing data to be used in query 
      $q = "INSERT INTO tblCompanyImg (CompanyID, ImgNum, ImgExt, ImgName, ImgImg) Values (1, 1, '$ext', '$title', '$base64')"; 
       $database->query($q); 

       $msg = "Success: image uploaded:"; 
      } 
     } 
     elseif (isset($_GET['title']))  // isset(..title) needed 
      $msg = 'Error: file not loaded';// to make sure we've using 
              // upload form, not form 
              // for deletion 
    } 
} 
?> 

而且我知道它是保存它在正確的,因爲我可以看到這樣的形象:

<?php 
    while($row = $database->fetch_array($result)) 
    { 
     $CompanyImgID = $row["CompanyImgID"]; 
     $CompanyID = $row["CompanyID"]; 
     $ImgName = $row["ImgName"]; 
     // outputing list 
     echo "<img src='data:image/jpeg;base64," . $row['ImgImg'] . "' />"; 
    } 
?> 

我想接下來做的是Visual Basic程序中查看上傳的圖片。

我嘗試這樣做:

Dim sSql As String = "Select * from tblCompanyImg Where CompanyImgID = 2" 
    Dim rSelect As New ADODB.Recordset 
    Dim img As Image 
    Dim imageBytes As Byte() 
    Dim ms As MemoryStream 

    With rSelect 
     .Open(sSql, MyCn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockOptimistic) 
     If Not .EOF Then 
      imageBytes = .Fields!ImgImg.Value 
      ms = New MemoryStream(imageBytes, 0, imageBytes.Length) 
      ms.Write(imageBytes, 0, imageBytes.Length) 
      img = Image.FromStream(ms, True) ' it fails right here: Parameter is not valid ' 
      LogoPictureBox.Image = img 
     End If 
     .Close() 
    End With 

,但它與一個錯誤參數img = Image.FromStream(ms, True)線路出現故障時無效。

有沒有更好的方式來讀取或寫入該數據庫以使其工作?

+3

提示:BLOB字段是用於二進制存儲。沒有必要base64編碼它。您只需將數據大小增加〜33%,稍後再強制執行額外的處理以再次對其進行解碼。 –

+0

你是說我可以這樣做:'$ base64 = chunk_split(base64_encode($ gambar));'並且放置'$ base64 = chunk_split($ gambar);'並讓它工作? – AndyD273

+0

沒有。只是'$ gambar = mysql_real_escape_string(file_get_contents($ _ FILES ['photo'] ['tmp_name']))',或者任何你的DB庫的等價函數。 –

回答

0
  • 爲什麼你基地64手之前解碼呢?
  • 我會建議保存在上傳memetype,確保理清ie即怪異的p-jpeg問題。

不管怎麼說,這是給你的一類。

MyImage.vb

Imports System.Data.SqlClient 
Imports System.IO 

Public Class MyImage 
    Implements IHttpHandler 

    Public Function GetImage(ByVal id As Integer, ByVal type As String) As Byte() 
     Dim Con As New SqlConnection(Common.ConnectionString) 
     Dim cmd As New SqlCommand 
     cmd.CommandText = _ 
      "Select * from tblCompanyImg Where CompanyImgID = @imgID" 
     cmd.CommandType = System.Data.CommandType.Text 
     cmd.Connection = Con 

     cmd.Parameters.AddWithValue("@imgID", id) 

     Con.Open() 
     Dim dReader As SqlDataReader = cmd.ExecuteReader 
     dReader.Read() 
     Dim img As Byte() 
     If dReader.HasRows Then 
      img = dReader("Image") 
     Else 
      Dim im As New ImageManipulator 
      Dim notfound = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Request.PhysicalApplicationPath & "Images\404.jpg") 
      img = im.ConvertImageToByteArray(notfound) 
     End If 

     Con.Close() 

     Return img 
    End Function 

    Function GetMEMEType(ByVal id As Integer) As String 
     Dim Con As New SqlConnection(Common.ConnectionString) 
     Dim cmd As New SqlCommand 
     cmd.CommandText = _ 
      "Select * from tblCompanyImg Where CompanyImgID = @imgID" 
     cmd.CommandType = System.Data.CommandType.Text 
     cmd.Connection = Con 

     cmd.Parameters.AddWithValue("@imgID", id) 

     Con.Open() 
     Dim dReader As SqlDataReader = cmd.ExecuteReader 
     dReader.Read() 
     Dim MEME As String 
     If dReader.HasRows Then 
      MEME = dReader("MEMEType") 
     Else 
      MEME = "image/jpeg" 
     End If 

     Con.Close() 

     Return If(MEME = "image/pjpeg", "image/jpeg", MEME) 
    End Function 

    Public ReadOnly Property IsReusable As Boolean Implements System.Web.IHttpHandler.IsReusable 
     Get 
      Return False 
     End Get 
    End Property 

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest 
     Dim path As String = context.Request.Path 
     Dim id = path.Split(".")(0).Split("/").Last ' not very pretty, grabs the id from the filename requested 
     Dim size = path.Split(".")(1) 'grabs the size required, thumb or full. 

     Dim imageData As Byte() = GetImage(id, size) 
     context.Response.OutputStream.Write(imageData, 0, imageData.Length) 
     'context.Response. 
     context.Response.ContentType = GetMEMEType(id) 
     'context.Response.AddHeader("content-disposition", "attachment; filename=img.jpg") 
    End Sub 
End Class 

然後在你的web.config堅持這個

<add verb="GET" path="*.jpg.db" type="project.MyImage,project" resourceType="Unspecified" name="databaseHandler" /> 

然後調用2.jpg.db將讓您的圖像文件。

+0

我有點試圖把兩個練習放在一起。首先是所有基於PHP的:讀取文件,將其編碼爲base64,將其放入blob中,然後在網頁加載時將其從數據庫中直接讀出並直接放入img src中,而無需將其寫回到文件系統。這就是base64的原因。我發現的例子是這樣做的,我還沒有找到一個更好的方法。這個新的項目不一定是base64,我只是想從那裏開始,因爲我已經在數據庫中有這些圖像了,如果它們可以互操作,它可能會很好。 – AndyD273

+0

是的,它很愚蠢 - 按照Marc的建議,只是忽略它。刪除上傳的圖像。 –

相關問題