B4J Question [Web App] Save file directly to the folder.

Chris Guanzon

Active Member
Licensed User
Longtime User
Hello,

Is it possible to save a file directly to a folder in a web app? I have PHP code that allows me to save a file in a folder.


upload.php:
<?php
$uploadDir = 'uploads/';
if (!empty($_FILES)) {
    $tempFile = $_FILES['file']['tmp_name'];
    $targetFile = $uploadDir . $_FILES['file']['name'];
    move_uploaded_file($tempFile, $targetFile);

    echo "completed";
}

Is it possible to accomplish this in a B4J web app?
 

Chris Guanzon

Active Member
Licensed User
Longtime User
Hi @aeric, could you teach me how to retrieve the body: formData in my B4J server? Here's the JavaScript code.


B4X:
// Configure Dropzone
    Dropzone.options.myDropzone = {
      init: function () {
        this.on("addedfile", function (file) {
          // Prepare the file for sending to REST API
          const formData = new FormData();
          formData.append("file", file);

          // Send the file to REST API
          fetch("rest_api_url", {
            method: "POST",
            body: formData,
          })
            .then(response => response.json())
            .then(data => {
              // Handle API response
              console.log(data);
            })
            .catch(error => {
              console.error("Error sending file:", error);
            });
        });
      },

B4X:
req.getparameter = ?
 
Last edited:
Upvote 0

aeric

Expert
Licensed User
Longtime User
Have you checked the example?

You need to check the FileHelper handler class and WebSocketWithFileUpload websocket class.

B4X:
Dim data As Map = ServletRequest.GetMultipartData(Main.TempDir, 100000)

B4X:
Public Sub FileUploaded(parts As Map)
    Dim filePart As Part = parts.Get("file1")
    Result.SetText("File uploaded successfully: " & filePart.SubmittedFilename & _
        " size = " & NumberFormat(File.Size("", filePart.TempFile) / 1000, 0, 2) & "kb")

    Result.SetCSS("color", "black")
    File.Delete("", filePart.TempFile)
    ws.Flush 'this is a server event so we need to explicitly call Flush
End Sub

Hint: use Log to debug the Part value
.
.
.
.
.
.
You can also check my Web API Template 2 where I don't use websocket. I have RequestMultipartList and RequestMultipartData subs in Utility class.
This hidden gem has nobody cares...
 
Upvote 0
Top