2013-11-21 85 views
3

我想從dropzone.js中base64編碼文件,並使用PJAX將其發送到處理程序頁面。不過,我有一個base64_data在POST請求中爲空的問題。使用base64編碼文件提交Dropzone.js

$(document).ready(function(){ 
    Dropzone.autoDiscover = false; 
    $("#file-form").dropzone({ 
     paramName: 'file', 
     clickable: true, 
     maxFilesize: 1, 
     uploadMultiple: false, 
     autoProcessQueue: false, 
     accept: function(file, done){ 
      reader = new FileReader(); 
      reader.onload = handleReaderLoad; 
      reader.readAsDataURL(file); 
      function handleReaderLoad(evt) { 
       document.getElementById("id_base64_data") 
        .setAttribute('value', evt.target.result); 
      } 
      document.getElementById("id_base64_name") 
       .setAttribute('value', file.name); 
      document.getElementById("id_base64_content_type") 
       .setAttribute('value', file.type); 
      form = $('#file-form'); 
      $.pjax({ 
       method: "POST", 
       container: "#pjax-container", 
       timeout: 2000, 
       url: "/upload/", 
       data: form.serialize(), 
      }); 
      done(); 
     }, 
    }); 
}); 

形式:

<form class="form-horizontal dropzone dz-clickable" id="file-form" action="/upload/" method="post" enctype="multipart/form-data" name="file-form"> 
    <input id="id_base64_data" name="base64_data" type="hidden"> 
    <input id="id_base64_name" name="base64_name" type="hidden"> 
    <input id="id_base64_content_type" name="base64_content_type" type="hidden"> 
    <div class="fileupload fileupload-new" data-provides="fileupload"> 
     <legend>Search for file</legend> 
    </div> 
<div class="dz-default dz-message"><span>Drop files here to upload</span></div> 
</form> 

任何提示?

回答

8

這是一個延遲handleReaderLoad發送pjax請求後執行的問題。工作示例:

$(document).ready(function(){ 
    Dropzone.autoDiscover = false; 
    $("#file-form").dropzone({ 
     paramName: 'file', 
     clickable: true, 
     maxFilesize: 1, 
     uploadMultiple: false, 
     autoProcessQueue: false, 
     accept: function(file, done){ 
      reader = new FileReader(); 
      reader.onload = handleReaderLoad; 
      reader.readAsDataURL(file); 
      function handleReaderLoad(evt) { 
       document.getElementById("id_base64_data") 
        .setAttribute('value', evt.target.result); 
       document.getElementById("id_base64_name") 
        .setAttribute('value', file.name); 
       document.getElementById("id_base64_content_type") 
        .setAttribute('value', file.type); 
       form = $('#file-form'); 
       $.pjax({ 
        method: "POST", 
        container: "#pjax-container", 
        timeout: 2000, 
        url: "/upload/", 
        data: form.serialize(), 
       }); 
      } 
      done(); 
     }, 
    }); 
}); 
+0

感謝您的支持! – azz0r

+0

感謝此片段:) – rmjoia