Bootstrap File Input Plugin

Asked

Viewed 1,263 times

1

Has anyone ever used this Bootstrap File Input Plugin with PHP? That is, making image insert in the database? I’m having difficulty taking the files from the "plugin" and not from the input file, to make the persistence.

Code

<form enctype="multipart/form-data" method="post" id="imagensSitio">
     <input id="file-0a" class="file" type="file" name="img[]" multiple="true" >
     <input type="submit" name="salvar" value="Salvar" class="btn btn-primary">
</form>

<script type="text/javascript">
jQuery(document).ready(function() { 
    jQuery('#imagensSitio').submit(function(){
        var dados = jQuery( this ).serialize();

        $.ajax({
            url: "crud/insere.php", // Url to which the request is sending
            type: "POST",             // Type of request to be send, called as method
            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false,        // To send DOMDocument or non processed data file it is set to false
            success: function(data)   // A function to be called if request succeeds
            {
                location.reload();
            }
        });
    });
});

$("#file-0a").fileinput({
    uploadUrl: "crud/insere.php",
    uploadAsync: false,
    minFileCount: 1,
    maxFileCount: 10,
    showUpload:true,
    showRemove:true
});
</script>

Insert.php

 include("../../../resources/conexao/conexao.php");
require ("../../../resources/wideImage/WideImage.php"); 

$nomeImg = $_FILES['img']['name'];
$nomeTmp = $_FILES['img']['tmp_name'];  

$extensao = array(".jpeg", ".jpg", ".png");

$dir_imagem = '../imagens/sitio/';

for($i = 0; $i < count($nomeTmp); $i++) {

    $extensao_img = strtolower(substr($nomeImg[$i],-4));

    if(in_array($extensao_img, $extensao)) {

        $novo_nome_imagem = date("Y.m.d-H.i.s") ."-". $i . $extensao_img;

        $imagem = WideImage::load($nomeTmp[$i]);
        $imagem = $imagem -> resize(770, 550, 'outside');

        if ($extensao_img == ".jpg" || $extensao_img == ".jpeg"){
            $imagem -> saveToFile($dir_imagem.$novo_nome_imagem, 85);
        } else if ($extensao_img == ".png") {
            $imagem -> saveToFile($dir_imagem.$novo_nome_imagem, 9);
        }

        $insert = "INSERT INTO sitio(imagem) VALUES ('$novo_nome_imagem')"; 
        $conexao = conexao();
        $PDO = $conexao->prepare($insert);
        $PDO -> execute();
        $conexao = null;                
    } 
}

Print page

inserir a descrição da imagem aqui

  • put the code you are using and what the return is taking...

  • No, I just do it the normal way, taking the images in the input file. If you know the plugin, after I choose the images, and if you delete one of them, before sending to the database, it considers the images of the input file, not those of the "plugin", understand?

  • what exactly is your question? input type="file" with document.getElementById("input").files

  • if you want to take the plugin images and insert/change in the database the plugin itself already makes available in the documentation how to using jquery.

  • right, and using PHP?

  • @Alisson when you try to get the array of files straight from the input type file with php is not coming the files you uploaded by the plugin? to pick up the files is the same way as if taken from a normal Input file.

  • When I delete a file in the plugin, at the time of inserting the array comes empty, that is, as if it had no file. Ah, I do the Insert with ajax. I deduced that it would not be the correct way to get normally from file input...

  • @Alisson I particularly see no problem picking from file input, the plugin itself inserts the files in the file input when you upload and remove also, so it is always in agreement with the plugin. They just created the "visual" for the input file. With me at least never gave any problem.

  • @Aldofernandesjunior I edited the topic with the source code, see. I took the example in a blog, but it does not roll, from the moment I delete a photo, and I give Submit, it not registered to the database, IE, the input file image array is probably empty. Any suggestions?

  • @Alisson your problem is that you want to delete a photo from the bank by this plugin by giving a post from an empty array?

  • @Aldofernandesjunior No, I want to take images from the computer and insert the name of the image in the database, normal, as a simple image crud. Put with this plugin I’m having trouble doing this. For example when I take the images and delete one and after I have the rest inserted in the database.

  • @Alisson, really the plugin has some features that it stops using only input type file and uses in other ways, so what I saw that you are using, not really to use the input itself, I did some tests here using the property itself uploadUrl plugin, always used the basic usage of this plugin, so I never needed to resort to other methods, take a look at what they themselves talk about uploading in AJAX, http://plugins.krajee.com/file-input#ajax-uploads, unfortunately I do not know your answer, I would have to do a search. then I will take another look.

  • Okay, I’ll take a look at what you’ve been through, if you have any news later, share it here. Thanks!

Show 8 more comments

1 answer

1

Jquery.serialize() you won’t be able to get the upload information. Try using the plugin ajaxform

An example of my jquery upload:

$('#enviar').click(function (Event) {
        Event.preventDefault();
        var base_url = '<?php echo base_url(); ?>';

        $('#frm').ajaxForm({
            dataType: 'json',
            url: base_url + 'local/inserir',
            resetForm: true,
            success: function (response) {
                if (response.resultado === true) {
                    $('.titulo').html('<h3>Cadastro realizado</h3>');
                    $('.mensagem').html(response.mensagem);
                    $('.modal-content').addClass('alert alert-success');
                    $('.modal').modal();
                } else {
                    $('.titulo').html('<h3>Atenção!</h3>');
                    $('.mensagem').html('Não foi possível cadastrar o projeto<br><hr>' + response.mensagem);
                    $('.modal-content').addClass('alert alert-warning');
                    $('.modal').modal();
                }
            },
            error: function () {
                $('.titulo').html('<h3>Atenção!</h3>');
                $('.mensagem').html('Não foi possível cadastrar o projeto<br><hr>' + response.mensagem);
                $('.modal-content').addClass('alert alert-warning');
                $('.modal').modal();
            }
        }).submit();
    })

NOTE: where this url: base_url + 'local/insert', you should put the page you will call.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.