B4J Question Binary data served from the server object

mrred128

Active Member
Licensed User
Longtime User
I have a server instance that needs to deliver jpg data through the servlet interface. A spinet of my code is as follows.....

B4X:
    Dim bc As ByteConverter
    Dim tp As InputStream = File.OpenInput(File.DirAssets,"myspecial.jpg")
    resp.ContentType = "image/jpeg"
    Dim buffer(tp.BytesAvailable) As Byte
    Dim count As Int = tp.ReadBytes(buffer,0,buffer.Length)
    If count <> -1 Then
        ' save as a file to verify we read the correct data
        Dim fo As OutputStream = File.OpenOutput("/","test.jpg",False)
        fo.WriteBytes(buffer,0,count)
        fo.Close
        ' one of many tries to send binary data
        Dim bc As ByteConverter
        Dim s As String = bc.StringFromBytes(buffer,"UTF-8")       
        Log(count & "," & s.Length)
        Dim a As Int
        resp.Write(s)
    End If
    tp.close

So, I have a jpg attached in the files tab. It get's correctly written in the "/test.jpg" file, verifying the binary read is correct. The log printed 328169,309773. The first number is the correct file & and data size.

I have tried many as many "write" conversions, but fear an oversight of a text only method is implemented.

Thoughts?
 

mrred128

Active Member
Licensed User
Longtime User
I guess I answered my own question. The secret is using the outputstream property.

B4X:
    Dim tp As InputStream = File.OpenInput(File.DirAssets,"myspecial.jpg")
    resp.ContentType = "image/jpeg"
    Dim buffer(tp.BytesAvailable) As Byte
    Dim count As Int = tp.ReadBytes(buffer,0,buffer.Length)
    If count <> -1 Then
        resp.OutputStream.WriteBytes(buffer,0,count)
    End If
    tp.close
 
Upvote 0
Top