Android Question upload a file to Localhost

khwarizmi

Active Member
Licensed User
Longtime User
Hi all

I tried to use UploadFilePhp library to upload a file to local host server, but always I get (fail).
B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example Upload
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim Up As UploadFilePhp
End Sub
Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Private Button1 As Button
    Private Button2 As Button
    Private Label1 As Label
    Private Label2 As Label
    Private ProgressBar1 As ProgressBar
    Dim Url_Php_Page As String
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout_upload")
 
    Url_Php_Page="http://192.168.8.4/upload_file.php"
    
    If FirstTime Then
        Up.B4A_log=True
        Up.Initialize("Up")
    End If
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean
   If KeyCode=KeyCodes.KEYCODE_BACK Then
   Dim domanda2 As Int
   domanda2 =  Msgbox2("Vuoi Uscire?","Avviso","Yes","","No",Null)
   If domanda2 = DialogResponse.POSITIVE Then
   Up.UploadKill
   ExitApplication
   Else If domanda2 = DialogResponse.NEGATIVE Then
   Return True
   End If
   End If
   Return True
End Sub
Sub Up_statusUpload (value As String)
    'Label1.Text=value
    'Label2.Text=value
End Sub
Sub Up_sendFile (value As String)
     Label2.Text=value
End Sub
Sub Up_statusVISIBLE (onoff As Boolean,value As String)
      Log(onoff&" \ "&value)
End Sub
Sub Button1_Click
Label1.Text=""
Label2.Text=""

Dim Path_Phone_Image As String
Path_Phone_Image = File.DirInternal & "/"  'OR  "/sdcard/
Dim name_image As String
    File.Copy(File.DirAssets,"1.jpg",File.DirInternal,"1.jpg")
name_image="1.jpg"
Up.doFileUpload( ProgressBar1,Label1,Path_Phone_Image & name_image,Url_Php_Page)   
End Sub
Sub Button2_Click
Label1.Text=""
Label2.Text=""
Dim Path_Phone_Image As String
Path_Phone_Image = File.DirInternal & "/"  'OR  "/sdcard/
Dim name_image As String
name_image="1.jpg"
Up.doFileUpload( Null,Null,Path_Phone_Image & name_image,Url_Php_Page)
End Sub

this is the php file:

B4X:
<?php
 
    $file_path = "uploads/";
    
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>
 

khwarizmi

Active Member
Licensed User
Longtime User
the error messages is (fail), which comes from the php file.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
try it with using error reporting
and add some logging

PHP:
<?php
error_reporting(E_ALL); // Enable Errors

    $file_path = "uploads/";
    echo $_FILES['uploaded_file']['name']; // Echo the name. Is it empty?
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
?>
 
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
unfortunately, php documentation regarding move_uploaded_files() only reports success or failure. it suggests 2 reasons for failure (1- no file exists and 2- no permission to write), but it doesn't allow for finding out which error occurred.
the user did not mention if line 5 of the php script produced any output:
B4X:
echo $_FILES['uploaded_file']['name']; // Echo the name. Is it empty?
that would at least indicate whether or not the uploaded file exists.
if the file exists, then, presumably, the user either does not have permission to write to the "uploads/" directory or that such a directory does not exist.
there is a
B4X:
fileperms ( string $filename ) : int
function in php. user might be able to query if permission to write is set and go from there.

if line 5 produces no output, then, presumably, the upload failed.
 
Upvote 0

khwarizmi

Active Member
Licensed User
Longtime User
the user did not mention if line 5 of the php script produced any output
did not give any results, even after I modified it to:
B4X:
 echo "filenames:" + $_FILES['uploaded_file']['name']; // Echo the name. Is it empty?
It appears that it cannot read originally from the php file.
Is the path incorrect?
B4X:
Up.doFileUpload( Null, Null, File.DirInternal & "/bbb.png" ,"http://192.168.8.5/upload_file.php")
Note that I can access the php file from the browser.
The problem is likely to be the permission.
 
Last edited:
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
It appears that it cannot read originally from the php file
Check the content of the hole _FILES array

PHP:
  foreach($_FILES as $fname => $fvalue){
    echo date("d.m.Y H:i:s", time()).": ".$fname."=".$fvalue."\r\n";
    #fwrite($file_handle, date("d.m.Y H:i:s", time()).": ".$fname."=".$fvalue."\r\n");
    foreach($fvalue as $name => $value){
      echo date("d.m.Y H:i:s", time()).": ".$name."=".$value."\r\n";
      #fwrite($file_handle, date("d.m.Y H:i:s", time()).": ".$fname."=".$fvalue."\r\n");
    }
  }
What is the output?

Under the line i STRONGLY suggest to use okhttputils2 instead of this old Library.

I tested it with

B4X:
    Dim files As List
    files.Initialize
    Dim fd As MultipartFileData
    fd.Initialize
    fd.KeyName = "GIF"
    fd.Dir = "E:\"
    fd.FileName = "bargraphmittimer.gif"
    fd.ContentType = "image/gif"
    files.Add(fd)

    Dim j As HttpJob
    j.Initialize("",Me)
    j.PostMultipart("https://domain/",CreateMap("action":"test"),files)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Dim res As String = j.GetString()
        Log(res)
    Else
        Log(j.ErrorMessage)
    End If
    j.Release

the result on PHP side was

24.02.2020 09:06:29: csv=Array
24.02.2020 09:06:29: name=bargraphmittimer.gif
24.02.2020 09:06:29: type=image/gif
24.02.2020 09:06:29: tmp_name=/tmp/phpQvu3Yw
24.02.2020 09:06:29: error=0
24.02.2020 09:06:29: size=313527

I tested it with B4J. But it works the same in B4A.

fd.Dir = "E:\" would be fd.Dir = File.DirAssets for ex.
 
Last edited:
Upvote 0

khwarizmi

Active Member
Licensed User
Longtime User
thanks @DonManfred
using OkHttpUtil2 (v2.9) and the same code:
B4X:
Try
        File.Copy(File.DirAssets,"Untitled (Time 0_00_07;05).png",File.DirInternal,"vv.jpg")
        Dim files As List
        files.Initialize
        Dim fd As MultipartFileData
        fd.Initialize
        fd.KeyName = "GIF"
        fd.Dir = File.DirInternal
        fd.FileName = "/vv.jpg"
        fd.ContentType = "image/jpg"
        files.Add(fd)
        Dim j As HttpJob
        j.Initialize("",Me)
        j.PostMultipart("http://192.168.8.4/upload_file.php",CreateMap("action":"test"), fd)
        Wait For (j) JobDone(j As HttpJob)
        If j.Success Then
            Dim res As String = j.GetString()
            Log(res)
        Else
            Log(j.ErrorMessage)
        End If
        j.Release
    Catch
        Log(LastException)
    End Try

I get this error:
(ClassCastException) java.lang.ClassCastException: b4a.example.httpjob$_multipartfiledata cannot be cast to java.util.List
 
Upvote 0
Top