преобразовать данные base64 в изображение с прокси-файлом в asp - PullRequest
1 голос
/ 08 марта 2012

Я пытаюсь преобразовать данные base64 в изображение с прокси-файлом, но код не работает.

Я добавил строку кодированных изображений base64 (base64String) в код для тестирования.

[update]

Я добавил альтернативный код ниже.Я думаю, что близко к решению, но есть проблема с кодировкой.

<%    Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
                "abcdefghijklmnopqrstuvwxyz" & _
                "0123456789" & _
                "+/"    

    Public Function base64_decode( byVal strIn )
        Dim w1, w2, w3, w4, n, strOut
        For n = 1 To Len( strIn ) Step 4
            w1 = mimedecode( Mid( strIn, n, 1 ) )
            w2 = mimedecode( Mid( strIn, n + 1, 1 ) )
            w3 = mimedecode( Mid( strIn, n + 2, 1 ) )
            w4 = mimedecode( Mid( strIn, n + 3, 1 ) )
            If w2 >= 0 Then _
                strOut = strOut + _
                    Chr( ( ( w1 * 4 + Int( w2 / 16 ) ) And 255 ) )
            If w3 >= 0 Then _
                strOut = strOut + _
                    Chr( ( ( w2 * 16 + Int( w3 / 4 ) ) And 255 ) )
            If w4 >= 0 Then _
                strOut = strOut + _
                    Chr( ( ( w3 * 64 + w4 ) And 255 ) )
        Next
        base64_decode = strOut
    End Function

    Private Function mimedecode( byVal strIn )
        If Len( strIn ) = 0 Then 
            mimedecode = -1 : Exit Function
        Else
            mimedecode = InStr( Base64Chars, strIn ) - 1
        End If
    End Function

    Function StringToBinary(String)
      Dim I, B
      For I=1 to len(String)
          B = B & ChrB(Asc(Mid(String,I,1)))
      Next
      StringToBinary = B
    End Function

    'values   
    base64String="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM///// wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="
    filename="test"


    'start 
    response.Expires = 0
    response.Buffer  = True
    response.Clear

    imgDataArr = split(base64String,";")
    mimeType = imgDataArr(0)
    imgData = split(imgDataArr(1),",")

    Response.contentType =mimeType 
    Response.AddHeader "Content-Disposition", "attachment; filename="&filename&".gif" 
    Response.binaryWrite StringToBinary(Base64Decode(imgData(1)))
    response.End
%>

<<< Обновленный код >>>

 <%     Function Base64Decode(base64String)
                  Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
                  Dim dataLength, sOut, groupBegin

                  base64String = Replace(base64String, vbCrLf, "")
                  base64String = Replace(base64String, vbTab, "")
                  base64String = Replace(base64String, " ", "")

                  dataLength = Len(base64String)
                  If dataLength Mod 4 <> 0 Then
                    Err.Raise 1, "Base64Decode", "Bad Base64 string."
                    Exit Function
                  End If

                  For groupBegin = 1 To dataLength Step 4
                    Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
                    numDataBytes = 3
                    nGroup = 0
                    For CharCounter = 0 To 3
                      thisChar = Mid(base64String, groupBegin + CharCounter, 1)
                      If thisChar = "=" Then
                        numDataBytes = numDataBytes - 1
                        thisData = 0
                      Else
                        thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1
                      End If
                      If thisData = -1 Then
                        Err.Raise 2, "Base64Decode", "Bad character In Base64 string."
                        Exit Function
                      End If
                      nGroup = 64 * nGroup + thisData
                    Next
                    nGroup = Hex(nGroup)
                    nGroup = String(6 - Len(nGroup), "0") & nGroup
                    pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
                      Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
                      Chr(CByte("&H" & Mid(nGroup, 5, 2)))
                    sOut = sOut & Left(pOut, numDataBytes)
                  Next
                  Base64Decode = sOut
            End Function

            Function Stream_StringToBinary(Text, chrSet)
                Const adTypeText = 2
                Const adTypeBinary = 1
                Dim BinaryStream 'As New Stream
                Set BinaryStream = CreateObject("ADODB.Stream")

                'Specify stream type - we want To save text/string data.
                BinaryStream.Type = adTypeText

                'Specify charset For the source text (unicode) data.
                If Len(chrSet) > 0 Then
                  BinaryStream.CharSet = chrSet
                Else
                  BinaryStream.CharSet = "us-ascii"
                End If

                'Open the stream And write text/string data To the object
                BinaryStream.Open
                BinaryStream.WriteText Text

                'Change stream type To binary
                BinaryStream.Position = 0
                BinaryStream.Type = adTypeBinary

                'Ignore first two bytes - sign of
                BinaryStream.Position = 0
                Stream_StringToBinary = (BinaryStream.Read)
            End Function


        'values   
        base64String="data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM///// wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="

        'start 
        response.Expires = 0
        response.Buffer  = True
        response.Clear

        imgDataArr = split(img,";")
        mimeType = imgDataArr(0)
        filename="testImage"
        extension = Split(imgDataArr(0),"/")(1)
        imgData = split(imgDataArr(1),",")

        Response.contentType = mimeType
        Response.AddHeader "Content-Disposition", "attachment; filename="&filename&"."&extension 
        Response.CharSet = "utf-8"
        Response.binaryWrite Stream_StringToBinary(Base64Decode(imgData(1)),"utf-8")
        Response.End
    %>

1 Ответ

4 голосов
/ 08 марта 2012

Использование свойств элементов документа xml упрощает преобразование двоичного файла из строки base64.Быстрый образец, рассмотрим это.

base64String = "data:image/gif;base64,R0lGODlhDwAPAKECAAAAzMzM///// wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4ML wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="

Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
    nodeB64.DataType = "bin.base64" ' stores binary as base64 string
    nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)

With Response
    .Clear
    .ContentType = "image/gif"
    .AddHeader "Content-Disposition", "attachment; filename=testImage.gif"
    .BinaryWrite nodeB64.NodeTypedValue 'get bytes and write
    .End
End With
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...