2017-08-07 121 views
0

我一直在爲此掙扎數日。 我正嘗試爲某人創建功能,以便使用FileUpload控件將圖像文件從本地機器上傳到FTP服務器。 問題是,FileUpload控件無法顯式檢索要從客戶機上傳的圖像的路徑,因此如果要從網上的任何pc上傳圖像,我無法動態獲取圖像的源路徑。 '排序'的唯一方法是獲取路徑,或者說流是使用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())

但我不知道是怎麼回事代碼IM將ImageUpload.PostedFile.InputStream()轉換爲能夠給我一個未失真圖像的字節。

回答

0

您不需要做任何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 
+0

FILESTREAM可是沒有一個。長度方法 –

+0

什麼是[這裏](https://開頭msdn.microsoft.com/en-us/library/system.io.filestream.length(v=vs.110).aspx)呢? –

+0

即使用FileStream類。上面的變量fileStream是StreamReader的類型 –