'Class module
Sub Class_Globals
'This map is just there to associate a given file with a location. This shows that each file
'can be located somewhere else and that location has no relationship to the www folder of the jServer
'application. This can be done any which way. Could just do one separate folder for all files. Do
'different folders for files with different extensions, etc. The sky's the limit. Could use a text file
'or database for file locations. Could use id#'s in the "GET" request and map them to file names/locations.
'And on and on
Private fileInfo As Map = CreateMap("file1.txt": "c:\temp", "file2.png": "c:\temp2")
Private contentTypes As Map = CreateMap("txt": "plain\text", "png": "image/png")
End Sub
Public Sub Initialize
End Sub
Sub Handle(req As ServletRequest, resp As ServletResponse)
If req.Method <> "GET" Then
resp.SendError(500, "method not supported.")
Return
End If
Dim fName As String = req.getParameter("filename")
'Here we are using the fileInfo map to retrieve necessary file information. This could
'be anything else as explained above.
If fileInfo.ContainsKey(fName) Then
Dim fExtension As String = GetExtension(fName)
If contentTypes.ContainsKey(fExtension) Then
resp.ContentType = contentTypes.Get(fExtension)
'If you don't want to have a default file name in the download dialog, then just do
'resp.SetHeader("Content-disposition", "attachment")
resp.SetHeader("Content-disposition", $"attachment; filename=${fName}"$)
Dim inStream As InputStream = File.OpenInput(fileInfo.Get(fName), fName)
Dim outStream As OutputStream = resp.OutputStream
File.Copy2(inStream, outStream)
Else
resp.SendError(500, "unsupported content type")
End If
Else
resp.SendError(404, "file not found")
End If
End Sub
'https://www.b4x.com/android/forum/threads/detect-extension-from-mime-type.58789/#post-415466
Sub GetExtension(strFileName As String) As String
If strFileName.IndexOf(".") > 0 Then
Dim parts() As String = Regex.Split("\.", strFileName)
Return parts(parts.Length - 1)
Else
Return Null
End If
End Sub