B4J Question File Upload

coldflame

Member
Good Morning Everyone, I am trying to create a B4J handler to help with file upload. When I make a call to the handler, a new file is created on the server however the file is empty(has 0kb size). Can someone please help?


Here is the code snippet
Handler Code:
Sub Handle(Req As ServletRequest, Resp As ServletResponse)
    Request = Req
    Response = Resp
   
    If Request.Method <> "POST" Then
        HttpUtility.ReturnErrorResponse("Only POST Request is allowed", 405, Response)
        Return
    End If
   
    ProcessRequest
End Sub

Private Sub ProcessRequest
    Dim In As InputStream = Request.InputStream
   
    Dim uploadDirectory As String = FileUtility.GetUploadDirectory(Main.Config.Get("DefaultUploadDirectory"))

    Dim mulitpartFormData As Map = Request.GetMultipartData(uploadDirectory, 10000000)
   
    Dim filePart As Part = mulitpartFormData.Get("file")
   
    Log($"filePart.SubmittedFilename => ${filePart.SubmittedFilename}"$)
   
   
    Dim newFileName As String = FileUtility.GenerateNewFileName(filePart.SubmittedFilename)
   
    Log($"newFileName => ${newFileName}"$)

    'Log($"filePart.TempFile => ${filePart.TempFile}"$)
   
    Dim out As OutputStream = File.OpenOutput(uploadDirectory, newFileName, False)
    File.Copy2(In, out)
    out.Close
End Sub

Thanks
 

Attachments

  • Screenshot from 2024-04-21 09-52-34.png
    Screenshot from 2024-04-21 09-52-34.png
    45.9 KB · Views: 16
  • Screenshot from 2024-04-21 09-56-33.png
    Screenshot from 2024-04-21 09-56-33.png
    14.5 KB · Views: 11
Solution
B4X:
 Dim out As OutputStream = File.OpenOutput(uploadDirectory, newFileName, False)
    File.Copy2(In, out)
    out.Close
This code is relevant when the file is uploaded as the POST payload directly. This is not the case with multipart requests.

You should instead copy the file with:
B4X:
File.Copy(filePart.TempFile, "", uploadDirectory, newFileName)

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
 Dim out As OutputStream = File.OpenOutput(uploadDirectory, newFileName, False)
    File.Copy2(In, out)
    out.Close
This code is relevant when the file is uploaded as the POST payload directly. This is not the case with multipart requests.

You should instead copy the file with:
B4X:
File.Copy(filePart.TempFile, "", uploadDirectory, newFileName)
 
Upvote 0
Solution

coldflame

Member
B4X:
 Dim out As OutputStream = File.OpenOutput(uploadDirectory, newFileName, False)
    File.Copy2(In, out)
    out.Close
This code is relevant when the file is uploaded as the POST payload directly. This is not the case with multipart requests.

You should instead copy the file with:
B4X:
File.Copy(filePart.TempFile, "", uploadDirectory, newFileName)
Thanks Chief. I really appreciate
 
Upvote 0
Top