Welcome to the nuBuilder Forums!

Register and log in to access exclusive forums and content available only to registered users.

file upload to an specific url/address

Questions related to using nuBuilder Forte.
toms
Posts: 785
Joined: Sun Oct 14, 2018 11:25 am

Re: file upload to an specific url/address

Unread post by toms »

It's not the complete code. This is the original one:
https://gist.github.com/matteomattei/e2 ... 73b2da2921
toms
Posts: 785
Joined: Sun Oct 14, 2018 11:25 am

Re: file upload to an specific url/address

Unread post by toms »

You've mixed up the different codes a little bit (e.g. added JavaScript to PHP)

To summarize,

1. Your html/javascript upload code should look something like this:

Code: Select all

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Ajax upload example</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: "/public_html/nuBuilder4/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 buf = '<ul class="list-group">';                                    
                                    buf+='<li class="list-group-item">'+result.data[0]+'</li>';
                                    $('#process_file').val(result.data[0]).change(); // add to field - just 1 file 
                                    $('#result').html('<strong>File uploaded:</strong>'+buf);
                                } 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">Ajax upload example</h3>
                    </div>
                    <div class="panel-body">
                        <form method="post" enctype="multipart/form-data"  action="/public_html/nuBuilder4/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>
And is added to a HTML object:
html_object_upload_html_javascript.png

2. process_file.php cotains just this code:

Code: Select all

<?php
// here we should add all validity checks on $_GET and $_POST
// before processing the files
$res = array(); 
foreach ($_FILES["files"]["error"] as $key => $error)
{
    if ($error == UPLOAD_ERR_OK)
    {
        $name = $_FILES["files"]["name"][$key];
        if(file_exists('uploads/'.$name))
        {
            unlink('uploads/'.$name);
        }
        move_uploaded_file( $_FILES["files"]["tmp_name"][$key], "uploads/" . $name);
        $res[] = $name;
    }
    else
    {
        echo json_encode(array('res'=>FALSE,'data'=>'Error uploading '.$name));
        exit(1);
    }
}
echo json_encode(array('res'=>TRUE,'data'=>$res));
exit(0);
3. The form's JavaScript code:

Code: Select all

if (nuFormType() == 'edit') {
  $('#process_product_id').find('option[value=""]').remove();
}

if (nuFormType() == 'browse') {
    $('[data-nu-column="4"]').each(function (index) { // change: file is in this column
        var cellId = $(this).attr('id');
        var cellValue = $('#' + cellId).html();
        if (cellValue != '') {
           var filePath = "https://otoraby.com/pk/uploads/" + cellValue; // change: path to the file         
         $('#' + cellId).html('<a href="'+filePath+'" download>Download</a>');
         $(this).attr('onclick', '');
        }
    });
}
You do not have the required permissions to view the files attached to this post.
omid020
Posts: 21
Joined: Mon Apr 16, 2018 9:12 am

Re: file upload to an specific url/address

Unread post by omid020 »

I did all above advices, this is html/javascript upload code:

Code: Select all

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Ajax upload example</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: "/pk/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 buf = '<ul class="list-group">';                                   
                                    buf+='<li class="list-group-item">'+result.data[0]+'</li>';
                                    $('#process_file').val(result.data[0]).change(); // add to field - just 1 file
                                    $('#result').html('<strong>File uploaded:</strong>'+buf);
                                } 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">Ajax upload example</h3>
                    </div>
                    <div class="panel-body">
                        <form method="post" enctype="multipart/form-data"  action="/pk/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>
I just removed this html code and related field because it is generated with JavaScript in browse form via process_file field:
... Then create a html object that displays a link to your file on the server
<a href="path_to_server/#myfilename#" download="path_to_server/#myfilename#">Download</a>
But I am very confused about this part of JS code:

Code: Select all

 $('#process_file').val(result.data[0]).change(); // add to field - just 1 file
It seems it does not work and does not add file name to related field of database (process_file).

Does above piece of code act after saving the process form?
toms
Posts: 785
Joined: Sun Oct 14, 2018 11:25 am

Re: file upload to an specific url/address

Unread post by toms »

Have you added an input object process_file to your form?
The success callback that gets invoked upon successful completion of an Ajax request. (File uploaded)
omid020
Posts: 21
Joined: Mon Apr 16, 2018 9:12 am

Re: file upload to an specific url/address

Unread post by omid020 »

toms wrote:Have you added an input object process_file to your form?
process_file.jpg
As you see the second field of browsed table has a Download link; I had added file name of that item manually to database field.
The success callback that gets invoked upon successful completion of an Ajax request. (File uploaded)
How it could insert file name to database while form is not saved or submitted and just the uploading process is done?
file_upload_sample.jpg
You do not have the required permissions to view the files attached to this post.
toms
Posts: 785
Joined: Sun Oct 14, 2018 11:25 am

Re: file upload to an specific url/address

Unread post by toms »

It looks like process_file is your html object. It's supposed to be a text input.
If true, rename your html object and create a process_file text input object.
omid020
Posts: 21
Joined: Mon Apr 16, 2018 9:12 am

Re: file upload to an specific url/address

Unread post by omid020 »

It looks like process_file is your html object.
Yup! that was the point :D
Thank you so much! Feeling happy to have a useful form!
toms
Posts: 785
Joined: Sun Oct 14, 2018 11:25 am

Re: file upload to an specific url/address

Unread post by toms »

Great! :D :D
admin
Site Admin
Posts: 2814
Joined: Mon Jun 15, 2009 2:23 am
Been thanked: 25 times

Re: file upload to an specific url/address

Unread post by admin »

.
Locked