我几天来一直在努力。 我正在尝试为某人创建功能,只需使用FileUpload Control将图像文件从本地计算机上传到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()转换为将给我一个未失真图像的字节。
答案 0 :(得分:1)
您不需要进行任何UTF编码或解码,也不需要StreamReader。抓住字节。
fileStream = ImageUpload.PostedFile.InputStream
Dim fileBytes(0 to fileStream.Length - 1) as Byte
fileStream.Read(fileBytes, 0, fileBytes.Length)
fileStream.Close()
或者,如果您希望将缓冲区作为返回值,则可以使用BinaryReader:
Using binaryReader As New BinaryReader(ImageUpload.PostedFile.InputStream)
fileBytes = binaryReader.ReadBytes(binaryReader.BaseStream.Length)
binaryReader.Close()
End Using