[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 363
  • Last Modified:

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.
0
Jason Evans
Asked:
Jason Evans
  • 2
1 Solution
 
newyuppieCommented:
i use like this:

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


the other option is maybe try on your existing code to add sourceStream.Flush() before closing it.
NY

0
 
newyuppieCommented:
Lenght is of course Length, typo
0
 
RamuncikasCommented:
Try changing Encoding from UTF8 to ASCII.
0
 
Jason EvansSenior Software DeveloperAuthor Commented:
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.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now