下载附件。无法转换类型为' System.String'的对象输入' System.Byte []'

时间:2015-10-19 10:32:47

标签: vb.net

我正在尝试在VB.NET中下载附件,但收到如下错误:

  

无法转换类型为' System.String'的对象输入' System.Byte []'

我的代码:

Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)

    Dim id As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
    Dim bytes As Byte()
    Dim fileName As String, contentType As String
    strQry = "select file_name, license_doc, file_type from Driver_Mas where Id=" & Val(id)

    Reader = Osql.ExecuteRead(strQry)
    While Reader.Read
        bytes = DirectCast(Reader.Item("license_doc"), Byte())            
        contentType = Reader.Item("file_type").ToString()
        fileName = Reader.Item("file_name").ToString()
        Response.Clear()
        Response.Buffer = True
        Response.Charset = ""
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.ContentType = contentType
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName)
        Response.BinaryWrite(bytes)
        Response.Flush()
        Response.End()
    End While
End Sub

1 个答案:

答案 0 :(得分:2)

您需要使用Encoding.GetBytes方法从字符串中获取字节。如有必要,您可以将UTF8更改为任何其他编码

bytes = Encoding.UTF8.GetBytes(Reader.Item("license_doc"))