Ver Mensaje Individual
  #1 (permalink)  
Antiguo 17/01/2014, 11:19
ZeThito
 
Fecha de Ingreso: septiembre-2010
Mensajes: 147
Antigüedad: 14 años, 5 meses
Puntos: 3
Busqueda Metodo POST Asincrónico jQuery-File-Upload

Hola amigos foreros,

Desde hace un tiempo que no he podido encontrar la forma de como programar bien el código usando este complemento jQuery-File-Upload

La mayor parte del objetivo de mi requerimiento funciona:

1.- Inserta todos los campos del formulario dentro de la BD.
2.- Guarda la imagen dentro de una ruta especifica.

Hasta acá todo va bien, pero lo que no he podido lograr es enviar los datos de forma sincrónica y no asincrónica con jQuery. (Cuando hago clic Start Upload, los datos se envían, pero se queda en la misma página)

Dejo un vídeo de ejemplo:

http://youtu.be/CAb30XUUSbc

El Código:


index.php
Código PHP:


    
<!-- The file upload form used as target for the file upload widget -->
 <
form id="fileupload" action="upload.php" method="POST" enctype="multipart/form-data">
    <
div class="row">

        <
label class="title">
            <
span>Title:</span><br>
            <
input name="title[]" class="form-control">
        </
label>
        <
label class="description">
            <
span>Description:</span><br>
            <
input name="description[]" class="form-control">
        </
label>

        <
div class="span16 fileupload-buttonbar">        
            <
div class="progressbar fileupload-progressbar"><div style="width:0%;"></div></div>
            <
span class="btn success fileinput-button">
                <
span>Add files...</span>
                <
input type="file" name="files[]" multiple>
            </
span>
        
            <!--/ 
Extra file input stop -->
            <
button type="submit" class="btn primary start">Start upload</button>
        </
div>
    </
div>
    <
br>
    <
div class="row">
        <
div class="span16">
            <
table class="zebra-striped"><tbody class="files"></tbody></table>
        </
div>
    </
div>
</
form>
    <
br>
</
div>
<!-- 
The blueimp Gallery widget -->
<
div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
    <
div class="slides"></div>
    <
h3 class="title"></h3>
    <
class="prev"></a>
    <
class="next"></a>
    <
class="close">×</a>
    <
class="play-pause"></a>
    <
ol class="indicator"></ol>
</
div>

<!-- 
The template to display files available for upload -->
<
script id="template-upload" type="text/x-tmpl">
{% for (var 
i=0filefile=o.files[i]; i++) { %}
    <
tr class="template-upload fade">
        <
td>
            <
span class="preview"></span>
        </
td>
        <
td>
            <
class="name">{%=file.name%}</p>
            <
strong class="error text-danger"></strong>
        </
td>
        <
td>
            <
class="size">Processing...</p>
            <
div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
        </
td>
        <
td>
            {% if (!
&& !o.options.autoUpload) { %}
                <
button class="btn btn-primary start" disabled>
                    <
class="glyphicon glyphicon-upload"></i>
                    <
span>Start</span>
                </
button>
            {% } %}
            {% if (!
i) { %}
                <
button class="btn btn-warning cancel">
                    <
class="glyphicon glyphicon-ban-circle"></i>
                    <
span>Cancel</span>
                </
button>
            {% } %}
        </
td>
    </
tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview"></span>
        </td>
    </tr>
{% } %}
</script>
</html> 
main.js
Código Javascript:
Ver original
  1. /*
  2.  * jQuery File Upload Plugin JS Example 8.9.0
  3.  * https://github.com/blueimp/jQuery-File-Upload
  4.  *
  5.  * Copyright 2010, Sebastian Tschan
  6.  * https://blueimp.net
  7.  *
  8.  * Licensed under the MIT license:
  9.  * http://www.opensource.org/licenses/MIT
  10.  */
  11.  
  12. /* global $, window */
  13.  
  14. $(function () {
  15.     $('#fileupload').fileupload({
  16.         type: "POST",
  17.         url: 'upload.php',
  18.         dataType: 'html',
  19.         sequentialUploads: true,
  20.         // Enable image resizing, except for Android and Opera,
  21.         // which actually support image resizing, but fail to
  22.         // send Blob objects via XHR requests:
  23.         disableImageResize: /Android(?!.*Chrome)|Opera/
  24.             .test(window.navigator && navigator.userAgent),
  25.         imageMaxWidth: 800,
  26.         imageMaxHeight: 800,
  27.         imageCrop: true // Force cropped images
  28.         });
  29.    
  30. });

upload.php
Código PHP:
<?php
$options 
= array(
    
'delete_type' => 'POST',
    
'db_host' => 'localhost',
    
'db_user' => 'root',
    
'db_pass' => '',
    
'db_name' => 'example',
    
'db_table' => 'files'
);


error_reporting(E_ALL E_STRICT);
require(
'server/php/UploadHandler.php');

class 
CustomUploadHandler extends UploadHandler {

    protected function 
initialize() {
        
$this->db = new mysqli(
            
$this->options['db_host'],
            
$this->options['db_user'],
            
$this->options['db_pass'],
            
$this->options['db_name']
        );
        
parent::initialize();
        
$this->db->close();
    }

    protected function 
handle_form_data($file$index) {
        
$file->title = @$_REQUEST['title'][$index];
        
$file->description = @$_REQUEST['description'][$index];
    }

    protected function 
handle_file_upload($uploaded_file$name$size$type$error,
            
$index null$content_range null) {
        
$file parent::handle_file_upload(
            
$uploaded_file$name$size$type$error$index$content_range
        
);
        if (empty(
$file->error)) {
            
$sql 'INSERT INTO `'.$this->options['db_table']
                .
'` (`name`, `size`, `type`, `url`, `title`, `description`)'
                
.' VALUES (?, ?, ?, ?, ?, ?)';
            
$query $this->db->prepare($sql);
            
$query->bind_param(
                
'sissss',
                
$file->name,
                
$file->size,
                
$file->type,
                
$file->url,
                
$file->title,
                
$file->description
            
);
            
$query->execute();
            
$file->id $this->db->insert_id;
        }
        return 
$file;
    }

    protected function 
set_additional_file_properties($file) {
        
parent::set_additional_file_properties($file);
        if (
$_SERVER['REQUEST_METHOD'] === 'GET') {
            
$sql 'SELECT `id`, `type`, `title`, `description` FROM `'
                
.$this->options['db_table'].'` WHERE `name`=?';
            
$query $this->db->prepare($sql);
             
$query->bind_param('s'$file->name);
            
$query->execute();
            
$query->bind_result(
                
$id,
                
$type,
                
$title,
                
$description
            
);
            while (
$query->fetch()) {
                
$file->id $id;
                
$file->type $type;
                
$file->title $title;
                
$file->description $description;
            }
        }
    }

    public function 
delete($print_response true) {
        
$response parent::delete(false);
        foreach (
$response as $name => $deleted) {
            if (
$deleted) {
                
$sql 'DELETE FROM `'
                    
.$this->options['db_table'].'` WHERE `name`=?';
                
$query $this->db->prepare($sql);
                 
$query->bind_param('s'$name);
                
$query->execute();
            }
        } 
        return 
$this->generate_response($response$print_response);
    }

}

$upload_handler = new CustomUploadHandler($options);

?>

Saludos.