从PHP保存文件到数据库,从VB.net中的数据库查看

时间:2012-12-12 16:10:48

标签: php sql vb.net

首先,我想说是的,我确实知道使用文件系统执行此操作只是将文件名/位置保存在数据库中是更好的方法,我可能会在最终版本中执行此操作。

这主要是一个实验/概念证明/学习机会。

我的PHP上传表单正在运行。它需要一个图像并将其转换为base64字符串并将其放入数据库表中的图像blob中。

<?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)行失败并出现错误参数无效。

有没有更好的方法来读取或写入数据库以使其工作?

1 个答案:

答案 0 :(得分:0)

  • 你为什么要先将64解码呢?
  • 我建议在上传时保存memetype,确保排除那些怪异的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将获取您的图像文件。