B4J Question Serve File For Download

paddy12309

Member
Licensed User
Hi Everyone,
Having a slow mind Friday, I have a handler that creates a CSV I want it then to serve this to download but having had a look around the forums haven't managed to get my head around it yet....
here's my handler
B4X:
'Handler class
Sub Class_Globals
    Private mreq As ServletRequest 'ignore
    Private mresp As ServletResponse 'ignore
'    Private sql1 As SQL
End Sub
Public Sub Initialize
    If Not(Main.sql1.IsInitialized) Then
        Log("ReInitialising SQL1")
        Main.sql1.Initialize2("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/liteip","Collator","liteip1234")
    End If
End Sub
Sub Handle(req As ServletRequest, resp As ServletResponse)
   
    Dim RS As ResultSet = Main.sql1.ExecQuery("SELECT * FROM Device JOIN DTDevice ON Device.DeviceSN = DTDevice.DeviceSN")
    File.Delete(File.DirApp, "SignalCreate.csv")
    Dim MyTextWriter As TextWriter
    'Line below assumes text file located in rootexternal. It will be created if not exist
    MyTextWriter.Initialize(File.OpenOutput(File.DirApp, "SignalCreate.csv",True))
    Do While RS.NextRow
        MyTextWriter.WriteLine(RS.GetInt("DTDevice.DeviceSN") & "," & RS.GetString("Device.Drawing") &"-"& RS.GetInt("Device.DeviceSN"))
    Loop
    MyTextWriter.Close
   
    RS.Close
   
    Dim text As String
    text = MyTextWriter
    resp.SetHeader("Content-disposition", $"attachment; filename=signalout.csv"$)
    Dim bytes() As Byte
    bytes = text.GetBytes("UTF8")
    resp.OutputStream.WriteBytes(bytes,0,bytes.Length)
End Sub
I get a file that has this in one cell and nothing else;
(BufferedWriter) java.io.BufferedWriter@b93bde

Any helps appreciated!
Paddy
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
 Dim text As String
    text = MyTextWriter
    resp.SetHeader("Content-disposition", $"attachment; filename=signalout.csv"$)
    Dim bytes() As Byte
    bytes = text.GetBytes("UTF8")
Should be:
B4X:
resp.SetHeader("Content-disposition", $"attachment; filename=signalout.csv"$)
Dim bytes() As Bytes = File.ReadBytes(File.DirApp, "SignalCreate.csv")

However for this to work correctly the handler must be configured as a single thread handler. The file is not really required. You can use OutputStream.InitializeToBytesArray instead (though the single handler solution is also fine).
 
Upvote 0
Top