Link to home
Start Free TrialLog in
Avatar of Jason Evans
Jason EvansFlag for United Kingdom of Great Britain and Northern Ireland

asked on

UTF8.GetBytes - Not getting the whole of JPG file.

Hi there.

I'm trying to upload a JPG file to a FTP server.  Here is a snippet:

      Dim sourceStream As New StreamReader(sImageURL) ' <-- eg C:\Test.jpg ( about 220KB in size)

      Dim fileContents() As Byte = UTF8.GetBytes(sourceStream.ReadToEnd())

      sourceStream.Close()
      oFTPRequest.ContentLength = fileContents.Length ' <-- Length is about 123KB????

Why is UTF8.GetBytes not returning the whole of the JPG file? I've checked the file and it's not corrupt or damaged, it's 220KB no problem. So why should the GetBytes method have an issue with the file?

Should I be using another technique for getting the bytes of a JPG file?

Cheers.
Jas.
ASKER CERTIFIED SOLUTION
Avatar of newyuppie
newyuppie
Flag of Ecuador image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Lenght is of course Length, typo
Try changing Encoding from UTF8 to ASCII.
Avatar of Jason Evans

ASKER

Hi there.

By using newyuppie's suggestion, I arrived at the following code, which works spot on:

Public Sub UploadImageToShop(ByVal sImageURL As String)

  Dim oFTPRequest As FtpWebRequest = CType(WebRequest.Create(HOST & REMOTE_FILE_DIR & "/test.jpg"), FtpWebRequest)

  oFTPRequest.Method = WebRequestMethods.Ftp.UploadFile

  oFTPRequest.Credentials = New NetworkCredential(USERNAME, PASSWORD)

  Dim fileStream As FileStream = New FileStream(sImageURL, FileMode.Open)
  Dim sourceStream As New BinaryReader(fileStream)

  Dim fileContents() As Byte = New Byte(sourceStream.BaseStream.Length) {}
 
  sourceStream.Read(fileContents, 0, sourceStream.BaseStream.Length)
  sourceStream.Close()

  oFTPRequest.ContentLength = fileContents.Length

  Dim requestStream As Stream = oFTPRequest.GetRequestStream()

  requestStream.Write(fileContents, 0, fileContents.Length)
  requestStream.Close()

End Sub

Cheers.
Jas.