1

我正在尝试从 SQL Server 数据库中提取 .NET 中的字节字符串并将其转换为图像。我的代码看起来像这样

Dim strqry As String = "SELECT preview FROM dbo.AmazonS3FilePreview WHERE fileKey ='" + incomingKey + "'"
    Dim myComm As SqlCommand = New SqlCommand(strqry, myConn)
    Dim resultReader As SqlDataReader = myComm.ExecuteReader
    Dim previewBytes As Byte() = Nothing
    While resultReader.Read()
        previewBytes = DirectCast(resultReader.Item("preview"), Byte())
    End While
    If Not previewBytes Is Nothing Then
        Dim ms As MemoryStream = New MemoryStream(previewBytes)
        Response.ContentType = "image/jpeg"
        Response.OutputStream.Write(ms.GetBuffer, 0, ms.GetBuffer.Length)
        Response.AddHeader("Content-Disposition", "attachment;filename=" + incomingKey)
    End If

但是在线上Response.OutputStream.Write(ms.GetBuffer, 0, ms.GetBuffer.Length)我收到一条错误消息UnauthorizedAccessException: MemoryStream's internal buffer cannot be accessed。我绝对可以读取数据库中的常规 char 列,为什么读取字节有问题?

4

1 回答 1

2

你不需要使用GetBuffer,无论如何你不应该使用(它是内部缓冲区,比实际数据大,所以它的长度没有意义)。实际上,您根本不需要 a MemoryStream,因为您已经有了字节。你可以这样做:

    Response.ContentType = "image/jpeg"
    Response.OutputStream.Write(previewBytes, 0, previewBytes.Length)
于 2012-11-20T20:21:26.537 回答