Javascript PHP中的Ajax上传文件

Javascript PHP中的Ajax上传文件,javascript,php,jquery,ajax,zend-framework2,Javascript,Php,Jquery,Ajax,Zend Framework2,在我的PHP应用程序中,我有一些由AJAX生成的内容,表单中有文件输入 此表单位于引导模式中。我使用jQuery文件上传插件5.26将一些数据写入输入并上传文件,效果很好 我通过单击另一个列表元素来关闭模式并异步加载相同的内容 我和以前一样,但我有一个错误:4 没有上载任何文件 我使用了相同的动作、相同的模式和形式,唯一的区别是我使用AJAX渲染了两次。有人能告诉我如何修复这个错误以及如何上传第二个文件吗 我想补充的是,来自文本输入的数据已更改,但$\u FILES是空数组 另一个信息是,当我第

在我的PHP应用程序中,我有一些由AJAX生成的内容,表单中有文件输入

此表单位于引导模式中。我使用jQuery文件上传插件5.26将一些数据写入输入并上传文件,效果很好

我通过单击另一个列表元素来关闭模式并异步加载相同的内容

我和以前一样,但我有一个错误:4

没有上载任何文件

我使用了相同的动作、相同的模式和形式,唯一的区别是我使用AJAX渲染了两次。有人能告诉我如何修复这个错误以及如何上传第二个文件吗

我想补充的是,来自文本输入的数据已更改,但
$\u FILES
是空数组

另一个信息是,当我第一次渲染视图时,我可以上载文件,关闭模态并上载第二个文件

问题是当我第二次渲染此视图并尝试上载文件时

AJAX发送帖子和获取视图:

 $.ajax({
            type: "POST",
            url: "/ksiazka/pobierz-partial",
            dataType : 'json',
            data: {             
                id: idObiektu,
                template: template,
                typ: typObiektu,
                fmodel: fmodel
            },
            success: function(data)
            {
                $('#ksiazka-tresc').html(data.html);
            }
        });
渲染视图:

public function pobierzPartialAction()
{       
   $request = $this->getRequest();
    if ($request->isPost()) {            

        $id = $request->getPost('id');      
        $templatka = $request->getPost('template');      
        $typ = $request->getPost('typ');      
        $fmodel = $request->getPost('fmodel');      

        /* @var $wartosciDoTemplatki \Obiekty\Model\Ommost */
        $wartosciDoTemplatki = $this->pobierzWartosciDoTemplatki($templatka, $id, $typ, $fmodel);                     

        $htmlViewPart = new ViewModel();
        $htmlViewPart->setTerminal(true)
            ->setTemplate('template/' . $templatka)
            ->setVariables(array(
                'wartosci' => $wartosciDoTemplatki        
            ));

        $htmlOutput = $this->getServiceLocator()
            ->get('viewrenderer')
            ->render($htmlViewPart);


        $jsonObject = \Zend\Json\Json::encode(array(
            'html' => $htmlOutput
        ), true);
        echo $jsonObject;
        return $this->response;
    }
}   
视图:

JS脚本:

var ul = $('#upload ul');

$('.file').click(function(e){
    e.preventDefault();

    // Simulate a click on the file input button
    // to show the file browser dialog

    $(this).parent().find('input').click();
});

// Initialize the jQuery File Upload plugin
$('#upload').fileupload({

    // This element will accept file drag/drop uploading
    dropZone: $('#drop'),
    pasteZone: $(document),
    // This function is called when a file is added to the queue;
    // either via the browse button, or via drag/drop:
    add: function (e, data) {

        var tpl = $('<li class="working"><input type="text" value="0" data-width="20" data-height="20"'+
            ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');

        // Append the file name and file size
        tpl.find('p').text(data.files[0].name)
                     .append('<b>' + formatFileSize(data.files[0].size) + '</b>');

        // Add the HTML to the UL element
        data.context = tpl.appendTo(ul);

        // Initialize the knob plugin
        tpl.find('input').knob();

        // Listen for clicks on the cancel icon
        tpl.find('span').click(function(){

            if(tpl.hasClass('working')){
                jqXHR.abort();
            }

            tpl.fadeOut(function(){
                tpl.remove();
            });

        });

        // Automatically upload the file once it is added to the queue
        var jqXHR = data.submit();
    },

    progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');
        }
    },

    fail:function(e, data){ 
        // Something has gone wrong!
        data.context.addClass('error');
    },

    done: function (e, data) {
    }

});
var ul=$('#上传ul');
$('.file')。单击(函数(e){
e、 预防默认值();
//模拟单击“文件输入”按钮
//显示“文件浏览器”对话框的步骤
$(this).parent().find('input')。单击();
});
//初始化jQuery文件上传插件
$('#upload').fileupload({
//此元素将接受文件拖放上载
dropZone:$(“#drop”),
粘贴区:$(文档),
//将文件添加到队列时调用此函数;
//通过浏览按钮或通过拖放:
添加:功能(e、数据){
var tpl=$('
  • '); //附加文件名和文件大小 tpl.find('p').text(data.files[0].name) .append(“”+formatFileSize(data.files[0].size)+“”); //将HTML添加到UL元素 data.context=tpl.appendTo(ul); //初始化旋钮插件 tpl.find('input').knob(); //收听“取消”图标上的单击 tpl.find('span')。单击(函数(){ if(tpl.hasClass(“工作”)){ jqXHR.abort(); } tpl.fadeOut(函数(){ tpl.remove(); }); }); //将文件添加到队列后自动上载该文件 var jqXHR=data.submit(); }, 进度:功能(e、数据){ //计算上载的完成百分比 var progress=parseInt(data.loaded/data.total*100,10); //更新隐藏的输入字段并触发更改 //让jQuery旋钮插件知道如何更新拨号盘 data.context.find('input').val(progress.change(); 如果(进度==100){ data.context.removeClass('working'); } }, 失败:函数(e,数据){ //出了点问题! data.context.addClass('error'); }, 完成:功能(e,数据){ } });
    我们还没有任何代码,但是
    ajax
    传输中最常见的错误是如何定义调用中的
    数据。我上传这样的文件:(试试看)


    在没有看到相关代码片段的情况下,此问题包含的信息不足,任何人都无法客观回答。请发布您的代码。至少您可以说,他们听到了您的声音
    <div class="modal fade bs-example-modal-lg" tabindex="-1" aria-hidden="true" id="ksiazkaFileUpload"><div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Dodawanie zdjęcia</h4>
      </div>
        <div class="modal-body" style="min-height: 450px" id="hide-spinner">
          <div class="row">
            <div class="col-sm-12">
                <form id="upload" method="post" action="/ksiazka/upload-file" enctype="multipart/form-data">            
                    <input type="hidden" name="model" value="<?php echo $wartosci['model-pliki'] ?>" />                    
                    <input type="hidden" name="tabela" value="<?php echo $wartosci['tabela-pliki'] ?>" />                    
                    <input type="hidden" name="MASTER_ID" />    
                    <?php if(isset($wartosci['OM_ID'])): ?>
                        <input type="hidden" name="OM_ID" value="<?php echo $wartosci['OM_ID'] ?>" />       
                    <?php endif ?>
    
                    <label for="NR">NR</label>
                    <input type="text" class="form-control" name="NR" />   
                    <label for="OPIS">Opis</label>
                    <input type="text" class="form-control" name="OPIS" />                     
                    <div id="drop" style="margin-top: 10px">
                        <input type="file"  name="upl"  />         
                        <a href="#" class="file btn btn-primary pull-right disabled"><i class="fa fa-plus"></i> Dodaj</a>
    
                    </div>                   
                    <ul style="margin-top: 20px">
                             The file uploads will be shown here 
                    </ul>
                </form>
            </div>
        </div>
      </div>      
    </div>
    
    public function uploadFileAction()
    {       
        $allowed = array('png', 'jpg', 'gif','zip', 'txt', 'rtf');       
    
        var_dump($_FILES, $_POST);
    
        if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0)
        { 
    
            $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
            if(!in_array(strtolower($extension), $allowed)){
                echo '{"status":"error"}';
                exit;
            }            
    
            $file = file_get_contents($_FILES['upl']['tmp_name']);             
    
            $idTypu = 2;
    
            $values = $_POST;
    
            $model = $values['model'];
            $tabela = $values['tabela'];              
    
            $values['ID_TYPU_PLIKU'] = $idTypu;
    
            $values['PLIK'] = 'empty_blob()';
            $values['OPIS'] = "'". $values['OPIS'] . "'";
            $values['NR'] = "'". $values['NR'] . "'";
    
            $values['NAZWA_PLIKU'] = "'". $_FILES['upl']['name'] . "'";
    
            unset( $values['model']);
            unset( $values['tabela']);
    
            $session = new \Zend\Session\Container('namespace');
            $zasobId = $session->item;     
    
            $zasob = $this->getZasobyTable()->zwrocSchematPoId($zasobId);
    
            $fun  = 'get' . $model . 'Table';           
    
            $this->$fun()->saveUploadedFile($file, $values, $tabela, $zasob);
            echo 'ok';
            exit;
        }
    
        echo '{"status":"error"}';
        exit;
    }
    
    var ul = $('#upload ul');
    
    $('.file').click(function(e){
        e.preventDefault();
    
        // Simulate a click on the file input button
        // to show the file browser dialog
    
        $(this).parent().find('input').click();
    });
    
    // Initialize the jQuery File Upload plugin
    $('#upload').fileupload({
    
        // This element will accept file drag/drop uploading
        dropZone: $('#drop'),
        pasteZone: $(document),
        // This function is called when a file is added to the queue;
        // either via the browse button, or via drag/drop:
        add: function (e, data) {
    
            var tpl = $('<li class="working"><input type="text" value="0" data-width="20" data-height="20"'+
                ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
    
            // Append the file name and file size
            tpl.find('p').text(data.files[0].name)
                         .append('<b>' + formatFileSize(data.files[0].size) + '</b>');
    
            // Add the HTML to the UL element
            data.context = tpl.appendTo(ul);
    
            // Initialize the knob plugin
            tpl.find('input').knob();
    
            // Listen for clicks on the cancel icon
            tpl.find('span').click(function(){
    
                if(tpl.hasClass('working')){
                    jqXHR.abort();
                }
    
                tpl.fadeOut(function(){
                    tpl.remove();
                });
    
            });
    
            // Automatically upload the file once it is added to the queue
            var jqXHR = data.submit();
        },
    
        progress: function(e, data){
    
            // Calculate the completion percentage of the upload
            var progress = parseInt(data.loaded / data.total * 100, 10);
    
            // Update the hidden input field and trigger a change
            // so that the jQuery knob plugin knows to update the dial
            data.context.find('input').val(progress).change();
    
            if(progress == 100){
                data.context.removeClass('working');
            }
        },
    
        fail:function(e, data){ 
            // Something has gone wrong!
            data.context.addClass('error');
        },
    
        done: function (e, data) {
        }
    
    });
    
          $.ajax({
            type: 'post',
            url: 'upload.php',
            data: new FormData($('form')[0]),
            processData: false,
            contentType: false,
            success: function (result) {
              //show a success message or something else
            }
          });