B4J Question Upload File to a Web Server

khwarizmi

Active Member
Licensed User
Longtime User
Hi all

How can I upload a file from my B4J application to a web server?
I tried to use a B4A library (Upload file with php) but there was an error while building the app:
Up.doFileUpload(Null,Null,path,\src\com\tadaros\plt\coursecontent.java:926: error: package android.widget does not exist
 
Solution
My method is by putting a small PHP script on the website and sending it the file using MultipartFileData:

B4X:
Dim Job As HttpJob
Job.Initialize("", Me)

Dim Link As String = "http://www.mysite.com/api.php" 'Link to the php script or API or anything that's going to receive the file
Dim Files As List
Dim mp As MultipartFileData
Files.Initialize

mp.Initialize
mp.Dir = File.DirApp & "/temp"  'File location
mp.FileName = "myfile.txt"
mp.KeyName = "file"
mp.ContentType = "text/html"   'You can use "application/octet-stream" for other types
Files.Add(mp)

Job.PostMultipart(Link, Null, Files)
Wait For (Job) JobDone(j As HttpJob)
If Not(j.Success) Then Log("FAILED")

This is the PHP script:

B4X:
<?php
$target_dir = "uploads/"...

MegatenFreak

Active Member
Licensed User
My method is by putting a small PHP script on the website and sending it the file using MultipartFileData:

B4X:
Dim Job As HttpJob
Job.Initialize("", Me)

Dim Link As String = "http://www.mysite.com/api.php" 'Link to the php script or API or anything that's going to receive the file
Dim Files As List
Dim mp As MultipartFileData
Files.Initialize

mp.Initialize
mp.Dir = File.DirApp & "/temp"  'File location
mp.FileName = "myfile.txt"
mp.KeyName = "file"
mp.ContentType = "text/html"   'You can use "application/octet-stream" for other types
Files.Add(mp)

Job.PostMultipart(Link, Null, Files)
Wait For (Job) JobDone(j As HttpJob)
If Not(j.Success) Then Log("FAILED")

This is the PHP script:

B4X:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
    echo "OK";
}
else {
    echo "ERROR";
}
?>
 
Upvote 1
Solution

khwarizmi

Active Member
Licensed User
Longtime User
Thanks MegatenFreak
It depends on the web server. You cannot upload files to a web server unless the server is configured to accept files and the actual details depend on the server configuration.
Thanks Erel
. I mean the web server that I use to host my website and database.
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…