upload image and save path to db

upload image and save path to db

niideaniidea Posts: 16Questions: 1Answers: 0
edited June 2016 in Free community support

Hello ,

I need to store the path of the file uploaded on the db but only get the ID. what am I doing wrong?

I have:

Editor::inst( $db, 'platos','pid' )
    ->fields(
        Field::inst( 'platos.pbid' )->validator( 'Validate::notEmpty' ),
        Field::inst( 'platos.pimg' )
            ->setFormatter( 'Format::ifEmpty', null )
            ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/zampa/resources/'.$_GET['bid'].'/ __NAME__ ' )          
                ->db( 'files', 'id', array(
                    'filename'    => Upload::DB_FILE_NAME,
                    'filesize'    => Upload::DB_FILE_SIZE,
                    'web_path'    => Upload::DB_WEB_PATH,
                    'system_path' => Upload::DB_SYSTEM_PATH
                ) )
                ->validator( function ( $file ) {
                    return $file['size'] >= 5000000 ?
                        "Files must be smaller than 5M" :
                        null;
                } )
                ->allowedExtensions( [ 'png', 'jpg', 'gif' ], "Please upload an image" )
            )
    )
    ->leftJoin('categorias','cid','=','platos.pcid')
    ->process( $_POST )
    ->json();

"platos.pimg" always shows: 23 or 24 or 25 ( id) instead of "name.jpg".

Please, can anyone help? Thank you in advance. :(

Sorry for my english.

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Are you using the display option of the upload field type? There is an example here and also documentation here.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0
    edited June 2016

    Hi Allan,

    Yes, I'm using the display option of the upload field type :

    editor = new $.fn.dataTable.Editor( {
            ajax: "editor.php?bid=<?php echo $_SESSION['bar']?>",
            table: "#platos",
            fields: [ {
                        type:    "hidden",
                        name:    "platos.pbid",
                        def: "<?php echo $bid?>"
                    }, { 
                        label: "Imagen:",
                        name: "platos.pimg",
                        type: "upload",
                        dragDrop: false,
                        display: function ( data, type,row ) {
                            return '<img height="40%" width="40%" src="../resources/<?php echo $bid?>/'+data+'"/>';
                        },                  
                        clearText: "Clear",
                        noImageText: 'No image'                 
                    }
                ],
                formOptions: {
                    inline: {
                        onBlur: 'submit'
                    }
                }
        } );
    

    Thank you very much for the help - I'm desperate -

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Can you give me a link to the page so I can take a look at the issue and see what the problem is please.

    I'm not even sure where it is displaying the number - is it in the Editor form, or the table?

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0
    edited June 2016

    http://drailine.com/draipanel/simple.php ( suomi / suomi )

    Try uploading an image to the row called "allan" ( or a new item)

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    The browser is showing me 404 errors for the uploaded file and a broken image icon where it should be displayed. I guess it isn't saving into the expected location:

    http://drailine.com/zampa/resources/2/35
    Failed to load resource: the server responded with a status of 404 (Not Found)

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Yes, That's the problem. I indicate in the code:

                ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/zampa/resources/'.$_GET['bid'].'/__NAME__' )            
    

    But... is saved as 'id' (http://drailine.com/zampa/resources/2/35)`
    instead of 'filename.jpg' (http://drailine.com/zampa/resources/2/cocktail-demo.jpg)

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Thanks for the clarification - I understand the issue now. I'll try to recreate the problem tomorrow morning. I've just taken a look at the code and don't see anything obvious unfortunately.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Hello Allan,

    Have you been able to discover anything?

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Hi,

    I'm afraid I haven't. i've just tried it locally:

    ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/upload/__NAME__' )
    

    and it appears to work without issue. The file is uploaded and saved with the original file name on the server. You have a couple of extra spaces around __NAME__ in your code above, but that wouldn't cause it to save by id.

    What version of the PHP libraries are you using for Editor?

    Regards,
    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Hi Allan,

    PHP Version 5.6.21 ( http://drailine.com/info.php )

    (The extra spaces was my mistake when writing this forum)

    Thanks for your help.

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Sorry - I was meaning the Editor libraries specifically rather than the PHP version. The current release of Editor (and its PHP libraries) is 1.5.6.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Sorry.

    I've updated now all versions:

    '''
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.1/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.0/css/select.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="examples/resources/syntax/shCore.css">
    <link rel="stylesheet" type="text/css" href="examples/resources/demo.css">
    <style type="text/css" class="init"></style>
    
    <script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.3.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.2.1/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/select/1.2.0/js/dataTables.select.min.js"></script>
    <script type="text/javascript" language="javascript" src="js/dataTables.editor.min.js"></script>
    <script type="text/javascript" language="javascript" src="//cdn.datatables.net/keytable/2.1.2/js/dataTables.keyTable.min.js"></script>
    

    '''

    same problem. :(

    I use the latest version (I bought a few days ago) : Editor-PHP-1.5.6

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    That's really odd! I'm afraid we'll need to do a bit of debugging as I don't understand why that isn't working.

    In Editor/Upload.php, right at the bottom you will find a function called _path.

    Could you update it to be:

        private function _path ( $name, $id )
        {
            $extn = pathinfo( $name, PATHINFO_EXTENSION );
    
            file_put_contents( '/tmp/editor-debug', '_path: '. $name .' - '. $id."\n", FILE_APPEND );
    
            $to = $this->_action;
            $to = str_replace( "__NAME__", $name, $to   );
            $to = str_replace( "__ID__",   $id,   $to   );
            $to = str_replace( "__EXTN__", $extn, $to );
    
            file_put_contents( '/tmp/editor-debug', '_path done: '. $name."\n", FILE_APPEND );
    
            return $to;
        }
    

    then upload a file and have a look at the file it has written (you may need to update the path to be suitable for your server). Then post the contents here?

    Thanks,
    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Indeed, I modified the path:

    file_put_contents( 'editor-debug', '_path: '. $name .' - '. $id."\n", FILE_APPEND );
    

    editor-debug file shows:

    _path: attr_sync.JPG - 42
    _path done: attr_sync.JPG
    _path: attr_sync.JPG - 42
    _path done: attr_sync.JPG
    

    (If you want I can provide you access via ftp)

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    That debug trace suggests that the name is correctly being used, so it must be getting altered somewhere else. Which leads me to look back at the Javascript being used:

    return '<img height="40%" width="40%" src="../resources/<?php echo $bid?>/'+data+'"/>';

    I think that data value is the issue - it should in fact be looking up the value using the file() method. Try:

    return '<img height="40%" width="40%" src="'+table.file( 'files', data ).web_path+'"/>';
    

    The reason being, is that you have the path stored in the web_path parameter, so let's use that. There is an example of that available here.

    If that fails, then yes, if you could send me a PM with the FTP details (click my name above and then the "Send message" button), that would be great.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    I tried to use it as shown in the shample. But the result was:
    TypeError: f.files[a] is undefined

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Hello Allan,

    Did you receive the credentials?

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Yes thank you - I was away yesterday and am just catching up now. I'll post back shortly when I look into it.

    Allan

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    I've just tried logging in, the FTP details are fine thanks. However, the web page isn't loading at all - it is string to reference a file that there is no information about. Looking at the PHP file (staff.php) there isn't an Upload instance defined at all. Was that changed since the end of last week? Above you have Upload information, but not on the server.

    Could you re-instate the code that had the problem we were discussing above so I can try to debug it please?

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Nothing has changed in the code since I reported the problem with the upload.

    For "Editor" i use a php file: "editor.php?bid=<?php echo $_SESSION['bar']?>",
    And for Datatable I use another php file: "staff.php"

    Why? If I use editor.php for datatable ... errors appear when I try to get the data from the db. I found that using 2 files ... everything works.

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    I see - thanks. I've changed it to both use editor.php and sent the bid parameter as GET for both.

    Now it gives an error because platos.pimg is being passed into the file() method as a file id, which it isn't - it appears to be a file name. I would have expected platos.pimg to be an id that refers to the files table's primary key column for the row relating to that file. Is that not the case? That's what Editor's upload features would expect. Is this data preexisting?

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    But an external application is using this database. And here (platos.img) the path of the image is saved. For this reason can not be the id. It must be a path.

    How could resolve this? I mandatorily need to store the path in that field ( platos.img)

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Thanks for the additional information. That helps.

    Do you have a separate table for the files (I think so, but want to check)? What is the foreign key relationship between the main table and the files table? Does the files table have any use outside of Editor, or are you only using it because its in the Editor example?

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Do you have a separate table for the files (I think so, but want to check)?
    No. Image path is stored on platos table. Image file is stores on filesystem.

    What is the foreign key relationship between the main table and the files table?
    I have 3 tables:
    - bar ( something like 'restaurant')
    - platos ( something like 'foods')
    - categorias ( something like 'categories')

    platos.pbid = bar.id
    platos.pcid = categorias.cid

    platos.pimg = image path for file saved in the filesystem

    Does the files table have any use outside of Editor, or are you only using it because its in the Editor example?
    Yes. The external app (mobile app) gets the image path and displays it

    Something like '$sql = "SELECT * FROM platos WHERE pbid =".$bid." and pcid=".$cat." order by porder, pnameES ASC" ;'

    Does that answer your questions?

    (If you need it, I can also give you access to db via phpMyAdmin)

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin

    Cool - thanks for the information. If you don't need any database interaction for the saved files, the first thing to do is remove the db() function call for the Upload instance.

    The next thing to do is remove any use of the file() API on the client-side. That is only useful if you use the database interaction. Instead, try:

    render: function (data, type, row) {
       return data;
    }
    

    for the image column. Then modify that renderer to return an img tag which loads the image using the path information. See the renderers documentation for details on how to use renderers.

    That should get you to the point where the table can at least be displayed - then we'll take it from there assuming that is successful.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Great, it seems we move forward.

    • I have removed any use of the file() API on the client-side. Now th image is displayed correctly
    • I have removed the db () function call fot the upload instace. Now the systemPath is stored in the db.
      How I could do to save only the filename in the db?
      platos.pimg = 'imagename.jpg' i
      sntead of
      platos.pimg = '/home/path/to/image/imagename.jpg'

    Further, how I could do to save only the filename in the db but save the file into a specific path?
    Why? Because I need:

    1. Store only the filename in the db
    2. Upload the file to a specific directory
    Field::inst( 'platos.pimg' )
                ->setFormatter( 'Format::ifEmpty', null )
                ->upload( Upload::inst( '../zampa/resources/'.$_GET['bid'].'/__NAME__' )
                    ->validator( function ( $file ) {
                        
                        return $file['size'] >= 5000000 ?
                            "Files must be smaller than 5M" :
                            null;
                    } )
                    ->allowedExtensions( [ 'png', 'jpg', 'gif' ], "Please upload an image" )
                ),
    

    Thanks

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin
    Answer ✓

    Great!

    How I could do to save only the filename in the db?

    What you need to do now is define a custom upload action. It might sound a bit painful, but it really isn't too bad! Basically you need a function that will save the file to wherever you want in the server's file system and then return what you want to use to identify the file (in this case the file name).

    If you have a look at the example shown in the above link, line 4 is saving the file (you'd use your ../zampa/... string (note you can't use __NAME__ you'd need to do that part in code - the $file parameter contains this information ($file['name']).

    Then just return the name.

    Hopefully that should be it.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Works! Thank you so much for all your help ( and patience)

    I have one more question: This page will be used for each user of the database. Each user has an bid associated. This bid is stored in the session when the user login. So I would like to filter the results by the bid.

    what is the problem?

        ->where( 'pbid',$_SESSION['bid'] )
    

    $_SESSION['bid'] always is empty in this php file...

    I guess the reason for this is that the same session is not shared. In this case, how I can send from the editor and datatable the 'bid' ? (this was the problem that I used 2 files php)

  • allanallan Posts: 63,258Questions: 1Answers: 10,421 Site admin
    Answer ✓

    Have you started the session in that PHP file? It should be quite possible to share the session.

    Allan

  • niideaniidea Posts: 16Questions: 1Answers: 0

    Hello Allan,

    Weir. I'd swear it was included. This has solved the problem.

    Enormously grateful for your help.

    Thnaks

This discussion has been closed.