<%
' 上传文件的最大尺寸（字节）
Const MaxUploadSize = 10485760 ' 10MB

' 数据库连接信息
Const ConnectionString = "DRIVER={MySQL ODBC 5.3 Unicode Driver}; SERVER=localhost; DATABASE=your_database; UID=your_username; PASSWORD=your_password;"

' 获取上传的文件
Dim uploadedFile
Set uploadedFile = Request.Files("imageFile")

If Not uploadedFile Is Nothing Then
    ' 检查文件大小
    If uploadedFile.Size > MaxUploadSize Then
        Response.Write("The uploaded file is too large.")
        Response.End
    End If

    ' 读取文件内容
    Dim stream
    Set stream = Server.CreateObject("ADODB.Stream")
    stream.Type = 1 ' adTypeBinary
    stream.Open
    stream.Write uploadedFile.Item("Value")
    stream.Position = 0
    Dim binaryFile
    binaryFile = stream.Read
    stream.Close
    Set stream = Nothing

    ' 连接数据库
    Dim conn, cmd, rs
    Set conn = Server.CreateObject("ADODB.Connection")
    conn.Open ConnectionString

    ' 检查是否已经有图片存在
    Set rs = conn.Execute("SELECT COUNT(*) AS ImageCount FROM images WHERE id = 1")

    If rs("ImageCount") > 0 Then
        ' 更新现有图片
        Set cmd = Server.CreateObject("ADODB.Command")
        cmd.ActiveConnection = conn
        cmd.CommandText = "UPDATE images SET image = ? WHERE id = 1"
        cmd.Parameters.Append cmd.CreateParameter("@image", 204, 1, LenB(binaryFile), binaryFile) ' 204: adLongVarBinary, 1: adParamInput
        cmd.Execute
        Set cmd = Nothing
    Else
        ' 插入新图片
        Set cmd = Server.CreateObject("ADODB.Command")
        cmd.ActiveConnection = conn
        cmd.CommandText = "INSERT INTO images (id, image) VALUES (1, ?)"
        cmd.Parameters.Append cmd.CreateParameter("@image", 204, 1, LenB(binaryFile), binaryFile) ' 204: adLongVarBinary, 1: adParamInput
        cmd.Execute
        Set cmd = Nothing
    End If

    ' 关闭连接
    conn.Close
    Set rs = Nothing
    Set conn = Nothing

    Response.Write("Image uploaded and saved to database successfully.")
Else
    Response.Write("No file was uploaded.")
End If

Function Base64Encode(binaryData)
    Dim stream
    Set stream = Server.CreateObject("ADODB.Stream")
    stream.Type = 1 ' adTypeBinary
    stream.Open
    stream.Write binaryData
    stream.Position = 0
    stream.Type = 2 ' adTypeText
    stream.Charset = "iso-8859-1"
    Base64Encode = stream.ReadText
    stream.Close
    Set stream = Nothing

    Dim xml
    Set xml = Server.CreateObject("MSXML2.DOMDocument.3.0")
    Dim elem
    Set elem = xml.createElement("base64")
    elem.dataType = "bin.base64"
    elem.nodeTypedValue = Base64Encode
    Base64Encode = elem.text
    Set elem = Nothing
    Set xml = Nothing
End Function
%>
