如何将 Stream 转换为 Byte()

How to convert Stream to Byte()

我已经为此苦苦挣扎了好几天。 我正在尝试为某人创建功能,以便使用 FileUpload 控件将图像文件从他们的本地计算机简单地上传到 FTP 服务器。 问题是,FileUpload 控件无法显式检索要从客户端计算机上传的图像的路径,因此如果要从网络上的任何 pc 上传图像,我无法动态获取图像的源路径。 'SORT OF' 获取路径的唯一方法,或者更确切地说,流是使用 FileUpload.PostedFile.inputStream。然而,这个问题是将图像转换为字节数组。到目前为止,我搜索过的功能都是以 0 字节将文件上传到服务器。 如果我使用 StreamReader(FileUpload.PostedFile.InputStream) 并通过使用 UTF8 编码获取字节,则上传的图像有字节但大于原始文件并且图像已损坏。

以下是我用来上传的代码

Public Sub Upload()
    'FTP Server URL.
    Dim ftp As String = "ftp://winhost1.axxesslocal.co.za"

    'FTP Folder name. Leave blank if you want to upload to root folder.
    Dim ftpFolder As String = "/httpdocs/images/"

    Dim fileBytes As Byte() = Nothing

    'Read the FileName and convert it to Byte array.
    Dim fileName As String = Path.GetFileName(ImageUpload.FileName)
    Using fileStream As New StreamReader(ImageUpload.PostedFile.InputStream)

        fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
        fileStream.Close()
    End Using

    'Create FTP Request.
    Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftp & ftpFolder & fileName), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.UploadFile

        'Enter FTP Server credentials.
        request.Credentials = New NetworkCredential("******", "******")
        request.ContentLength = fileBytes.Length
        request.UsePassive = True
        request.UseBinary = True
        request.ServicePoint.ConnectionLimit = fileBytes.Length
        request.EnableSsl = False

    Using requestStream As Stream = request.GetRequestStream()
            requestStream.Write(fileBytes, 0, fileBytes.Length)
            requestStream.Close()
        End Using

        Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)


        response.Close()

End Sub

我知道问题出在这里 fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())

但我不知道还有什么其他方法可以将 ImageUpload.PostedFile.InputStream() 转换为字节,从而得到不失真的图像。

您不需要进行任何 UTF 编码或解码,也不需要 StreamReader。只需抓住字节。

fileStream = ImageUpload.PostedFile.InputStream
Dim fileBytes(0 to fileStream.Length - 1) as Byte
fileStream.Read(fileBytes, 0, fileBytes.Length)
fileStream.Close()

或者,如果您希望接收缓冲区作为 return 值,您可以使用 BinaryReader:

Using binaryReader As New BinaryReader(ImageUpload.PostedFile.InputStream)
    fileBytes = binaryReader.ReadBytes(binaryReader.BaseStream.Length)
    binaryReader.Close()
End Using