<!--#include file="db.asp"-->
<%
Dim conn, rs, cmd
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open Str

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

Dim uploadedFile, binaryFile, imageBase64, stream

' 处理文件上传
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    Dim boundary, contentType, rawData, position, startPos, endPos, fileData, fileHeader, fileHeaderEndPos
    contentType = Request.ServerVariables("CONTENT_TYPE")

    If InStr(contentType, "multipart/form-data") > 0 Then
        boundary = "--" & Mid(contentType, InStr(contentType, "boundary=") + 9)
        rawData = Request.BinaryRead(Request.TotalBytes)

        ' 记录调试信息
        Response.Write("Boundary: " & Server.HTMLEncode(boundary) & "<br>")
        Response.Write("Raw Data Length: " & LenB(rawData) & "<br>")

        ' 输出部分原始数据以进行调试
        Dim rawDataPreview
        rawDataPreview = MidB(rawData, 1, 100)
        Response.Write("Raw Data Preview (first 100 bytes): " & Server.HTMLEncode(BinaryToString(rawDataPreview)) & "<br>")

        ' 确保边界字符串存在于原始数据中
        position = InStrB(rawData, boundary)
        If position = 0 Then
            Response.Write("Boundary not found in raw data.<br>")
        Else
            Response.Write("Initial boundary position: " & position & "<br>")
            position = position + LenB(boundary) + 2 ' 跳过边界和回车换行符

            ' 查找文件头结束位置
            fileHeaderEndPos = InStrB(position, rawData, vbCrLf & vbCrLf)
            If fileHeaderEndPos = 0 Then
                Response.Write("File header end not found.<br>")
            Else
                fileHeader = MidB(rawData, position, fileHeaderEndPos - position)
                startPos = fileHeaderEndPos + 4 ' 跳过文件头后的两个回车换行符
                endPos = InStrB(startPos, rawData, vbCrLf & boundary) - 2 ' 找到下一个边界

                ' 记录调试信息
                Response.Write("File Header: " & Server.HTMLEncode(BinaryToString(fileHeader)) & "<br>")
                Response.Write("Start Position: " & startPos & "<br>")
                Response.Write("End Position: " & endPos & "<br>")

                If startPos > 0 And endPos > 0 Then
                    fileData = MidB(rawData, startPos, endPos - startPos)

                    ' 检查文件大小
                    If LenB(fileData) > MaxUploadSize Then
                        Response.Write("The uploaded file is too large.")
                        Response.End
                    End If

                    ' 读取文件内容
                    Set stream = Server.CreateObject("ADODB.Stream")
                    stream.Type = 1 ' adTypeBinary
                    stream.Open
                    stream.Write fileData
                    stream.Position = 0
                    binaryFile = stream.Read ' Read as binary data
                    stream.Close
                    Set stream = Nothing

                    ' 检查是否已经有图片存在
                    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

                    Response.Write("Image uploaded and saved to database successfully.")
                Else
                    Response.Write("Failed to process uploaded file.<br>")
                    Response.Write("Start or End position is invalid.<br>")
                End If
            End If
        End If
    Else
        Response.Write("No file was uploaded.<br>")
    End If
End If

' 获取并显示当前图片
Set rs = conn.Execute("SELECT image FROM images WHERE id = 1")
If Not rs.EOF Then
    Dim byteData
    byteData = rs("image")
    imageBase64 = "data:image/jpeg;base64," & Base64Encode(byteData)
Else
    imageBase64 = ""
End If

rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing

Function BinaryToString(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 = "utf-8"
    BinaryToString = stream.ReadText
    stream.Close
    Set stream = Nothing
End Function

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

    Base64Encode = CStr(Base64Encode) ' 确保返回的是字符串

    ' 确保Base64编码安全
    Base64Encode = Replace(Base64Encode, vbCrLf, "")
    Base64Encode = Replace(Base64Encode, vbLf, "")
    Base64Encode = Replace(Base64Encode, vbCr, "")
End Function
%>

<!DOCTYPE html>
<html>
<head>
    <title>Upload and Update Image</title>
</head>
<body>
    <h1>Upload and Update Image</h1>
    <form action="upimg.asp" method="post" enctype="multipart/form-data">
        <input type="file" name="imageFile">
        <input type="submit" value="Upload Image">
    </form>
    
    <% If imageBase64 <> "" Then %>
        <h2>Current Image:</h2>
        <img src="<%=imageBase64%>" alt="Current Image" style="max-width: 300px; max-height: 300px;">
    <% End If %>
</body>
</html>
