jQuery

2011-10-26 14 views
17

Im la costruzione di un caricamento di file con jQuery, ma Im ottenendo un errore di jQuery cercando di impostare gli attributi della forma:jQuery

$(document).ready(function() { 
    $("#formsubmit").click(function() { 

     var iframe = $('<iframe name="postframe" id="postframe" class="hidden" src="about:none" />'); 

     $('div#iframe').append(iframe); 

     $('#theuploadform').attr("action", "/ajax/user.asmx/Upload") 
     $('#theuploadform').attr("method", "post") 
     $('#theuploadform').attr("userfile", $('#userfile').val()) 
     $('#theuploadform').attr("enctype", "multipart/form-data") 
     $('#theuploadform').attr("encoding", "multipart/form-data") 
     $('#theuploadform').attr("target", "postframe") 
     $('#theuploadform').submit(); 
     //need to get contents of the iframe 

     $("#postframe").load(
      function() { 
       iframeContents = $("iframe")[0].contentDocument.body.innerHTML; 
       $("div#textarea").html(iframeContents); 
      } 
     ); 
    } 
); 


<div id="uploadform"> 
    <form id="theuploadform" action=""> 
     <input id="userfile" name="userfile" size="50" type="file" /> 
     <input id="formsubmit" type="submit" value="Send File" /> 
    </form> 
</div> 

<div id="iframe" style="width: 0px; height: 0px; display: none;"> 
</div> 

<div id="textarea"> 
</div> 
+0

Qual è lo scopo di questa linea? '$ ('# theuploadform'). attr (" userfile ", $ ('# userfile'). val())' il browser non ha effettivamente accesso al valore degli input del file per ragioni di sicurezza, restituirà qualche percorso fasullo. –

+0

Hai sbagliato, puoi leggere il valore, ma non cambiarlo. –

+1

Cosa restituisce il valore? Ho detto che restituirà un valore, ma non il percorso effettivo del file. –

risposta

52

Ho trovato la soluzione. Questo codice funziona:

<script type="text/javascript"> 

    $(document).ready(function() { 

     $("#formsubmit").click(function() { 

      var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>'); 

      $("body").append(iframe); 

      var form = $('#theuploadform'); 
      form.attr("action", "/upload.aspx"); 
      form.attr("method", "post"); 

      form.attr("encoding", "multipart/form-data"); 
      form.attr("enctype", "multipart/form-data"); 

      form.attr("target", "postiframe"); 
      form.attr("file", $('#userfile').val()); 
      form.submit(); 

      $("#postiframe").load(function() { 
       iframeContents = this.contentWindow.document.body.innerHTML; 
       $("#textarea").html(iframeContents); 
      }); 

      return false; 

     }); 

    }); 

</script> 


<form id="theuploadform"> 
    <input id="userfile" name="userfile" size="50" type="file" /> 
    <input id="formsubmit" type="submit" value="Send File" /> 
</form> 

<div id="textarea"> 
</div> 
+0

grazie così tanto che ho trascorso le età che cercano di lavorare fuori, per coloro che possono trovare ora, si noti che si dovrebbe usare e.preventDefault non return false e rimuove l'iFrame all'inizio della funzione se esiste se prevedi di caricare più file usando questo –

+1

Grazie, il tuo codice oscilla! – rom

+1

Grazie, codice semplice e fai il lavoro, meglio di tutti i tutorial che ho letto! – IgorOliveira

0

Sai, invece di andare a prendere lo stesso articolo più volte, perché non basta riutilizzarlo:

var form = $('#theuploadform'); 
form.attr("action", "/ajax/user.asmx/Upload"); 
form.attr("method", "post"); 
// and so on 

Che tipo di errore stai riscontrando? puoi postarlo?

UPDATE

Poiché non è possibile impostare l'attributo da soli: ecco un lavoro intorno:

Mettere il modulo in un iframe, e allegare un evento onchange al pulsante di ingresso. quando l'utente seleziona un file, si attiva il codice necessario per caricare il file (invio), quindi la finestra principale può chiudere l'iframe.

+0

è semplice non permettermi di impostare il profilo utente attr. –

+0

@myself, vedere il mio aggiornamento – Ibu

1

vostro obiettivo modulo deve essere lo stesso nome iframe, ad esempio:

<form target="frame" 
     action="http://posttestserver.com/post.php?dir=example" 
     method="post" 
     enctype="multipart/form-data"> 
    <input name="file" type="file"/> 
</form> 

<iframe name="frame"></iframe> 

E dopo questo evento è possibile allegare al tasto di ingresso per l'ascolto di 'cambiamento'. Furthemore è possibile ottenere progressi dal server utilizzando jsonp e tutto questo funzionerà in qualsiasi evento del browser IE3 +. Qualcosa di simile a questo:

$('input').change(function() { 
    $('form').submit(); 
}); 

$.getJSON('/echo/jsonp/?callback=?', function(e, progress) { 
    console.log(progress); 
}); 
3

Non è un plugin ufficiale, tuttavia ecco un esempio di come si potrebbe avvolgere la logica della presentazione del modulo in un plugin.

Esempio:

<form method="post" enctype="multipart/form-data"> 
    <input name="file" type="file" /> 

    <input type="text" name="test" /> 

    <button type="submit">Submit</button> 
</form> 

<script> 
    $('form').submit(function (e) { 

     //prevent default submit 
     e.preventDefault(); 

     //submit through frame 
     $(this).frameSubmit({ 
      done: function (form, frame, options) { 
       console.log('done!'); 
      }, 
      fail: function (form, frame, options) { 
       console.log('fail!'); 
      }, 
      always: function (form, frame, options) { 
       console.log('always!'); 
      } 

      //custom hasError implementation if needed 
      //by default if the frame's body HTML contains the text "unexpected error" or "server error" 
      //it is treated as an error 
      /*,hasError: function (frame) { 
       return false; 
      }*/ 
     }); 
    }); 

</script> 

PLUGIN

!function ($, doc) { 
    var _frameCount = 0, 
     _callbackOptions = ['done', 'fail', 'always'], 
     _hasFailed = function (frame) { 
      var frameHtml = $(frame).contents().find('body').html(); 

      return /(server|unexpected)\s+error/i.test(frameHtml); 
     }, 
     _createFrame = function() { 
      return $('<iframe>').prop('name', 'jq-frame-submit-' + _frameCount++).hide().appendTo(doc.body); 
     }; 

    $.fn.extend({ 
     frameSubmit: function (options) { 

      return this.each(function() { 
       var deferred = $.Deferred(), 
        form = this, 
        initialTarget = form.target, 
        hasTarget = form.hasAttribute('target'), 
        hasFailed = options.hasFailed || _hasFailed, 

        //The initial frame load will fire a load event so we need to 
        //wait until it fires and then submit the form in order to monitor 
        //the form's submission state. 
        $frame = _createFrame().one('load', function() { 
         $frame.one('load', function() { 
          deferred[hasFailed(this) ? 'reject' : 'resolve'](form, this, options); 
          $frame.remove(); 
         }); 

         form.submit(); 

         //restore initial target attribute's value 
         if (hasTarget) form.target = initialTarget; 
         else form.removeAttribute('target'); 
        }); 

       //attach handlers to the deferred 
       $.each(_callbackOptions, function (i, optName) { 
        options[optName] && deferred[optName](options[optName]); 
       }); 

       //make sure the form gets posted the to iframe 
       form.target = $frame.prop('name'); 
      }); 
     } 
    }); 
}(jQuery, document);