B4J Question PostMultipart: upload file with some POST parameters

peacemaker

Expert
Licensed User
Longtime User
HI, All

I'm trying to upload file by PHP script
PHP API:
<?
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);    //
require_once 'lib/funcs.php';


    if (!isset($_POST['key']) || $_POST['key'] == ''){
        echo json_encode(array('ret'=>'error', 'msg'=>'No APIkey'), JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (!isset($_POST['timestamp']) || $_POST['timestamp'] == ''){
        echo json_encode(array('ret'=>'error', 'msg'=>'No timestamp'), JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (!isset($_POST['agent']) || $_POST['agent'] == ''){
        echo json_encode(array('ret'=>'error', 'msg'=>'No agent'), JSON_UNESCAPED_UNICODE);
        exit;
    }

    $key = $_POST['key'];
    $timestamp = $_POST['timestamp'];
    $agent = isset($_POST['agent'])?SpecialChars($_POST['agent']):'';
    $valid_key = CheckAPIkey($key, $timestamp, $agent);

    if(!$valid_key){
        echo json_encode(array('ret'=>'error', 'msg'=>'Wrong APIkey'), JSON_UNESCAPED_UNICODE);
        exit;
    }

///var/www/hosting_user84488/data/www/domain_name/folder

$obd = ini_get('open_basedir');
$obd = str_replace(':.', '', $obd);
$path = $obd.'/www/domain_name/';

//--------------upload files ---------------------
function sendResponse($code = 200, $data = null)
{
    header('Content-Type: application/json');
    http_response_code($code);
    echo json_encode($data);
    die();
}

if (!empty($_FILES['uploaded_file']) && isset($_POST['upload_dir'])) {
    $filesize = $_FILES["uploaded_file"]["size"];
    $filename = basename($_FILES['uploaded_file']['name']);
    $filetmp = $_FILES['uploaded_file']['tmp_name'];
    $upload_dir = $_POST['upload_dir'];
    $path = $path . $upload_dir . '/' . $filename;

    // // validate filesize
    // if ($filesize > (1024 * 500)) {
    //     sendResponse(400, [
    //         'ret' => 'error',
    //         'msg' => 'max. filesize 500kb',
    //         'file' => $filename
    //     ]);
    // }

    if (move_uploaded_file($filetmp, $path)) {
        //file_put_contents(realpath($path) . ".txt", round(microtime(true) * 1000));
        sendResponse(200, [
            'ret' => 'ok',
            'msg' => 'Uploaded OK',
            'file' => $filename,
            'size' => filesize($path),
            'upload_dir' => $upload_dir
        ]);
    } else {
        sendResponse(500, [
            'ret' => 'error',
            'msg' => 'Error while uploading',
            'file' => $filename
        ]);
    }

}



?>

by MultiPart POST.
Debugging by the https://web.postman.co/

B4X:
Private Sub UploadHTTP_File(remoteFolder As String, localFileFullPath As String)
    If File.Exists(localFileFullPath, "") = False Then Return
   
    Dim fn As String = File.GetName(localFileFullPath)
    Dim localFolder As String = File.GetFileParent(localFileFullPath)
    Dim job As HttpJob
    job.Initialize("UploadHTTP_File", Me)
    Dim fd As MultipartFileData
    fd.Initialize
    fd.KeyName = "uploaded_file"
    fd.Dir = localFolder
    fd.FileName = fn
    'fd.ContentType = "*/*"
    Dim L As List
    L.Initialize
    L.Add(fd)
    Dim m As Map
    m.Initialize
    m.Put("upload_dir", remoteFolder)
    m.Put("agent", others.Get_DeviceID)
    m.Put("key", API_KEY.ToLowerCase)
    Dim timestamp As Long = DateTime.Now / 1000
    m.Put("timestamp", timestamp)
   
    job.PostMultipart(apif_HTTPURL, m, L)
   
    Wait For (job) JobDone(job As HttpJob)

If to do it by B4J as is in the code (by request NameValues parameters map) - no POST params on the server PHP side received, 'No APIkey' reply from PHP.
If by Postman to set the parameters in the body as "form-data" - the POST parameters are OK.
How to implement by B4J correctly ?
 
Last edited:

peacemaker

Expert
Licensed User
Longtime User
oops, all works, if to make correct path in the PHP-script.
The topic can be deleted.
 
Upvote 0
Top