<%
' 设置页面的编码为 UTF-8，防止中文乱码
Response.CodePage = 65001
Response.Charset = "UTF-8"

' 创建数据库连接
Dim conn, cmd, sql, binData, boundary, fileDataStart, fileDataEnd, fileSize, fileData, posStart, posEnd
Set conn = Server.CreateObject("ADODB.Connection")
str="dsn=conn;Driver={mysql driver};server=192.168.2.56;Port=3306;uid=root;pwd=bohaosoftware19711978;database=bohaosupermarket3;charset=utf8"
conn.Open str

' 检查是否有上传文件
If Request.TotalBytes > 0 Then
    ' 读取上传的图片数据
    binData = Request.BinaryRead(Request.TotalBytes) ' 读取所有上传的二进制数据
    
    ' 解析 multipart/form-data 的边界字符串
    boundary = GetBoundary(binData)
    If boundary <> "" Then
        ' 查找文件数据的起始和结束位置
        fileDataStart = GetFileStart(binData, boundary)
        fileDataEnd = GetFileEnd(binData, boundary, fileDataStart)

        ' 检查文件数据是否解析正确
        If fileDataStart > 0 And fileDataEnd > fileDataStart Then
            fileData = MidB(binData, fileDataStart, fileDataEnd - fileDataStart)
            ' 插入文件数据到数据库
            sql = "INSERT INTO images (image) VALUES (?)"
            Set cmd = Server.CreateObject("ADODB.Command")
            Set cmd.ActiveConnection = conn
            cmd.CommandText = sql
            cmd.Parameters.Append cmd.CreateParameter(, 204, 1, LenB(fileData), fileData) ' 204 = adLongVarBinary
            cmd.Execute
            Response.Write "Image upload successful!"
        Else
            Response.Write "Failed to extract the file, file data could not be located."
        End If
    Else
        Response.Write "Failed to parse the boundary."
    End If
Else
    Response.Write "Please select a file before uploading."
End If

' 关闭数据库连接
conn.Close
Set conn = Nothing

' 辅助函数：从表单数据中获取边界字符串
Function GetBoundary(binData)
    Dim posCrLf, boundary
    posCrLf = InStrB(binData, ChrB(13) & ChrB(10)) ' 查找回车换行符的位置
    If posCrLf > 0 Then
        boundary = MidB(binData, 1, posCrLf - 1) ' 提取 boundary 字符串
    Else
        boundary = ""
    End If
    GetBoundary = boundary
End Function

' 辅助函数：找到文件内容的起始位置
Function GetFileStart(binData, boundary)
    Dim posBoundaryEnd
    posBoundaryEnd = InStrB(binData, ChrB(13) & ChrB(10) & ChrB(13) & ChrB(10)) ' 找到文件内容的开始位置
    If posBoundaryEnd > 0 Then
        GetFileStart = posBoundaryEnd + 4 ' 返回文件起始位置
    Else
        GetFileStart = -1 ' 如果未找到，返回 -1
    End If
End Function

' 辅助函数：找到文件内容的结束位置
Function GetFileEnd(binData, boundary, startPos)
    Dim posBoundary
    posBoundary = InStrB(startPos, binData, "--" & boundary) ' 查找文件结束位置
    If posBoundary > 0 Then
        GetFileEnd = posBoundary - 2 ' 返回文件结束位置
    Else
        GetFileEnd = -1 ' 如果未找到，返回 -1
    End If
End Function
%>

<html>
<head>
    <title>Image Upload</title>
    <meta charset="UTF-8"> <!-- 设置页面编码为 UTF-8 -->
</head>
<body>
    <form action="?" method="post" enctype="multipart/form-data">
        <label>Select an image:</label>
        <input type="file" name="image" accept="image/*">
        <input type="submit" value="Upload Image">
    </form>
</body>
</html>