upload file to server

Questions related to customising nuBuilder Forte with Javascript or PHP.

upload file to server

Postby johan » Fri Nov 15, 2019 5:01 am

Hi
We've adjusted the script so we can upload files to our server
Code: Select all
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Bestanden toevoegen</title>
        <link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
        <script type="text/javascript">
            function TransferCompleteCallback(content){
                // we might want to use the transferred content directly
                // for example to render an uploaded image
            }

            $( document ).ready(function() {
                var input = document.getElementById("input_files");
                var formdata = false;

                if (window.FormData) {
                    formdata = new FormData();
                    $("#btn_submit").hide();
                    $("#loading_spinner").hide();
                }

                $('#input_files').on('change',function(event){
                    var i = 0, len = this.files.length, img, reader, file;
                    //console.log('Number of files to upload: '+len);
                    $('#result').html('');
                    $('#input_files').prop('disabled',true);
                    $("#loading_spinner").show();
                    for ( ; i < len; i++ ) {
                        file = this.files[i];
                        //console.log(file);
                        if(!!file.name.match(/.*\.pdf$/)){
                                if ( window.FileReader ) {
                                    reader = new FileReader();
                                    reader.onloadend = function (e) {
                                        TransferCompleteCallback(e.target.result);
                                    };
                                    reader.readAsDataURL(file);
                                }
                                if (formdata) {
                                    formdata.append("files[]", file);
                                }
                        } else {
                            $("#loading_spinner").hide();
                            $('#input_files').val('').prop('disabled',false);
                            alert(file.name+' is not a PDF');
                        }
                    }
                    if (formdata) {
                        $.ajax({
                            url: "/vrijwilligers/process_files.php",
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false, // this is important!!!
                            success: function (res) {
                                var result = JSON.parse(res);
                                $("#loading_spinner").hide();
                                $('#input_files').val('').prop('disabled',false);
                                if(result.res === true){
                                    var files = new Array;
                                    var buf = '<ul class="list-group">';
                                    for(var x=0; x<result.data.length; x++) {
                                      buf+='<li class="list-group-item">'+result.data[0]+'</li>';
                                      files.push(result.data[x]);
                                    }
                                    buf+='</ul>';
                                    $('#result').html('<strong>Files uploaded:</strong>'+buf);

                                    nuSetProperty('myfiles',JSON.stringify(files));
                                } else {
                                    $('#result').html(result.data);


                                }
                                // reset formdata
                                formdata = false;
                                formdata = new FormData();
                            },
                   error: function(jqXHR, textStatus, errorThrown) {
                      alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
                      console.log('jqXHR:');
                      console.log(jqXHR);
                      console.log('textStatus:');
                      console.log(textStatus);
                      console.log('errorThrown:');
                      console.log(errorThrown);
                   },
                        });
                    }
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <div id="container" style="margin-top:50px;">
            <div class="col-sm-offset-2 col-sm-8">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Bestanden</h3>
                    </div>
                    <div class="panel-body">
                        <form method="post" enctype="multipart/form-data"  action="/vrijwilligers/process_files.php">
                            <input type="file" name="files[]" id="input_files" multiple />
                            <button type="submit" id="btn_submit" class="form-control">Upload Files!</button>
                        </form>
                        <br />
                        <div id="loading_spinner"><i class="fa fa-spinner fa-pulse"></i> Uploading</div>
                        <div id="result"></div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>


This works but problem is that I can't upload multiple files in 1 session (I have to leave the form before I can upload a new file. Otherwise the new file overwrite te first file.
Other problem is that we use sessionid as filename to be sure the name is unique. Is there a better way to solve this?

Johan
johan
 
Posts: 306
Joined: Sun Feb 27, 2011 7:46 pm
Location: Belgium

Re: upload file to server

Postby Janusz » Fri Nov 15, 2019 5:53 am

maybe this can help
https://artisansweb.net/drag-and-drop-m ... t-and-php/

based on that I was implementing file storage in my applications and works very well - I can transfer as many files as I want with drag and drop but typically I am limiting to 10files per one transfer together with max file size and batch file size check. To the file name you can add nuID() to make sure they are unique
Janusz
 
Posts: 292
Joined: Fri Dec 28, 2018 10:11 pm
Location: Krakow, Poland

Re: upload file to server

Postby johan » Fri Nov 15, 2019 6:00 am

Jamusz
Do you have a working example of multiple upload files to your server within nubuilder?
I'm not an expert using php of jquery

Johan
johan
 
Posts: 306
Joined: Sun Feb 27, 2011 7:46 pm
Location: Belgium

Re: upload file to server

Postby Janusz » Fri Nov 15, 2019 7:14 am

Hi,
I will prepare a file - as I had to cut a small part from quite a big application and will send soon - after some more checking.
For the moment just a ad-hoc movie how it works - you will not see other windows from which I was downloading files as recording was limiting only to nuBuilder window.

https://drive.google.com/file/d/1VeBG57 ... sp=sharing
Janusz
 
Posts: 292
Joined: Fri Dec 28, 2018 10:11 pm
Location: Krakow, Poland

Re: upload file to server

Postby Janusz » Fri Nov 15, 2019 8:19 am

Please find enclosed .sql file.
You need to create uploads folder in you main nuBuilder directory on the server.
database: TxDB / globeadmin

https://drive.google.com/open?id=1SRrhd ... XkbIkYtodh
Janusz
 
Posts: 292
Joined: Fri Dec 28, 2018 10:11 pm
Location: Krakow, Poland

Re: upload file to server

Postby Janusz » Fri Nov 15, 2019 8:26 am

and add this file on the server in the main folder as: savetoserver.php

Code: Select all
<?php   // ver 2.0

$rap1= $_COOKIE['rap1_cookie'];
echo 'File(s) upload status: ';

foreach($_FILES['myFile']['name'] as $key=>$val){
    $file_name = $_FILES['myFile']['name'][$key];
// get file extension
    $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
// get filename without extension
    $filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);

$filenamewithoutextension=str_replace("+", "_", $filenamewithoutextension);
$filenamewithoutextension=str_replace(" ", "_", $filenamewithoutextension);
$filenamewithoutextension=str_replace(".", "_", $filenamewithoutextension);
$filenamewithoutextension=str_replace(",", "_", $filenamewithoutextension);

    if (!file_exists(getcwd(). '/uploads')) {
        mkdir(getcwd(). '/uploads', 0777);
    }

    $filename_to_store = $filenamewithoutextension. '_' .$rap1. '.' .$ext;
    move_uploaded_file($_FILES['myFile']['tmp_name'][$key], getcwd(). '/uploads/'.$filename_to_store);

if (file_exists(getcwd().'/uploads/'.$filename_to_store)) {echo ' OK ';}
                                                   else   {echo ' NOK! ';}
}

echo "\r\n";
echo "Verify NOK files - and reload them";

die;
?>
Janusz
 
Posts: 292
Joined: Fri Dec 28, 2018 10:11 pm
Location: Krakow, Poland

Re: upload file to server

Postby johan » Fri Nov 15, 2019 5:10 pm

Janusz

Thanks for your input.
That's not exactly what I'm looking for.
In my form I've added a subform with the files uploaded to the server that belongs to this form. Actualy I insert Record_id and filename into a table. In that case I only can insert 1 row in 1 session.

Johan
Attachments
Selectie_173.png
Selectie_173.png (18.46 KiB) Viewed 1241 times
johan
 
Posts: 306
Joined: Sun Feb 27, 2011 7:46 pm
Location: Belgium

Re: upload file to server

Postby kev1n » Fri Nov 15, 2019 5:42 pm

Just to get you right: Do you want to be able to upload one file per subform row and does your current script save the filename in the main form table?
You would have to save the filenames in the subform table.
kev1n
 
Posts: 728
Joined: Mon Oct 15, 2018 2:13 am

Re: upload file to server

Postby johan » Fri Nov 15, 2019 7:01 pm

Kev1n
No
When I upload a file the file is saved in a folder on my server. The link to the file is saved in a row on the subform. That"s what I want. I use this in after save of the form
Code: Select all
{
$json = json_decode("#myfiles#");

foreach ($json as $row)
{
 
   $query ="INSERT ignore into zzsys_bijlagen (bl_vw_id, bl_name)  VALUES ('#RECORD_ID#', '" . $row . "' ) ";
        nuRunQuery( $query);   
}

}


But
I only can upload 1 file, then I have to close my form, reopen it and upload another file.
johan
 
Posts: 306
Joined: Sun Feb 27, 2011 7:46 pm
Location: Belgium

Re: upload file to server

Postby kev1n » Sat Nov 16, 2019 12:29 am

I think you should have one upload button (Input File Object) per row. When a file is uploaded, the filename is stored in a field in that row.
kev1n
 
Posts: 728
Joined: Mon Oct 15, 2018 2:13 am

Next

Return to Custom Code