B4J Question [BANano] [SOLVED] How can I upload a file using Php?

Mashiane

Expert
Licensed User
Longtime User
Hi there

I'm trying to upload a file to the assets folder. As a non-expert (javascript + BANano) person what I'm trying is not working yet. I've tried to adopt an example that I was previously provided as a solution to these file management things by Kiffi.

I have attached here my example code for anyone willing to help me out. This is an example I have found on the internet and just updated it to suit my needs so that I can achieve my problem statement as per subject of this question.

B4X:
#if javascript
    function uploadFile(fileid){
        var fi = document.getElementById(fileid);
        var file = fi.files[0];       
        var url = './assets/upload.php';
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
            }
        };
        fd.append("upload_file", file);
        xhr.send(fd);
    }
#End If

This I have tried to adopt for BAnano like this...

B4X:
Sub UploadIt(id As String)
    'get the file input
    Dim fi As BANanoElement = BANAno.GetElement($"#${id}"$)
    'get the selected files, if any
    Dim files() As String = fi.ToObject.GetField("files").Result
    'loop though each selected file
    For fCnt = 0 To files.Length - 1
        'create a new formdata
        Dim fd As BANanoObject
        fd.Initialize2("FormData", Null)
        fd.SetField("upload_file", files(fCnt))
        Dim result As String = BANAno.CallAjaxWait("./assets/upload.php","POST","",fd,True,Null)
        Log(result)
    Next
End Sub

Both these in my event handler return a 'fail'

B4X:
Sub globalevent(event As BANanoEvent)
    Select Case event.ID
    Case "fu"
        BANAno.RunJavascriptMethod("uploadFile", Array As String("fu"))
        'UploadIt("fu")
    End Select
End Sub

Thanks in advance for your help
 

Attachments

  • FileUpload.zip
    2.3 KB · Views: 413

eric19740521

Member
Licensed User
Longtime User
banano b4j:
Sub UploadIt(id As String)
    'get the file input
    Dim fi As BANanoElement = BANano.GetElement($"#${id}"$)
    'get the selected files, if any
    Dim files() As String = fi.ToObject.GetField("files").Result
    'loop though each selected file
    For fCnt = 0 To files.Length - 1
        'create a new formdata
        Dim fd As BANanoObject
        fd.Initialize2("FormData", Null)
        'fd.SetField("upload_file", files(fCnt))
        fd.RunMethod("append", Array("upload", files(fCnt)))        '<=== change this
        
        Dim result As String = BANano.CallAjaxWait("/FileUpload","POST","",fd,True,Null)
        Log(result)
    Next
End Sub
 
Upvote 0
Top