2014-11-14 65 views
0

我已經有圖片上傳代碼,它運行良好,它只有一個圖片上傳選項。使用jquery將圖片上傳兩次

這裏的圖像發送到將在其中上傳並返回圖片src代碼和圖像路徑的功能,一旦返回它將在$('#image').html(data);

它的工作原理很好,當我有一個選項來填補,而我有兩個上載失敗,

我面臨的誤差爲它工作在第一

<input type="file" id="image" name="image" class="upload-img" style="opacity:0"> 

並且當我試圖第二

<input type="file" id="imagetwo" name="imagetwo" class="upload-img" style="opacity:0"> 

它在第一輸入類型替換圖像,

我已經在第二函數的第一函數和$('#imagetwo').html(data);$('#image').html(data);

我使用$("form#data").submit(function(){}

下面是HTML:

<input type="file" id="image" name="image" class="upload-img" style="opacity:0"> 
<input type="hidden" class="imagetextbox" name="imagetextbox"/> 

這裏是腳本:

<script> 
     $(document).ready(function() 
     { 
     $("form#data").submit(function(){ 
      var formData = new FormData($(this)[0]); 
      $.ajax({ 
       url: 'globalimageupload', 
       type: 'POST', 
       data: formData, 
       async: true, 
       success: function (data) 
       { 
       $('#image').html(data); 
       console.log(data);    
       }, 
       cache: false, 
       contentType: false, 
       processData: false 
      }); 
      return false; 
     }); 
      $("input[type='file']").on("change", function() 
      { 
      $("form#data").submit(); 
     }); 
     }); 
     </script> 

這裏是圖像處理函數:

public function globalimageupload() 
    { 
     $file = Input::file('image'); 
     if (Input::file('image')) 
     { 
      $valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions 
      $max_size = 2000 * 1024; // max file size (200kb) 
      $ext = $file->guessClientExtension(); 
      $size = $file->getClientSize(); 
      if (in_array($ext, $valid_exts) AND $size < $max_size) 
      { 
       $image=Input::file('image'); 
       $destinationPath = public_path()."/assets/uploads/companylogo/"; 
       $num_unique = md5(uniqid() . time()); 
       $fileName=$num_unique.'.'.$ext; 
       Input::file('image')->move($destinationPath,$fileName); 
       $desPathimg=public_path()."assets/uploads/companylogo/".$fileName; 
       $desPath=$fileName; 
       return HTML::image('assets/uploads/companylogo/'.$fileName,'photo', array('width' => 128, 'id'=> 'po', 'name'=> 'po', 'height' => 128)).'<input type="hidden" name="imagetextbox" id="imagetextbox" value="'.$desPath.'">'; 
      } 
      else 
      { 
       return 'Check the Extension and file size'; 
      } 
     } 
     else 
     { 
        return "Please upload any Image"; 
     } 
    } 

什麼是我做的錯誤,我怎樣才能解決這一問題?

回答

0

使用解除綁定功能之前綁定提交事件如下:

$("input[type='file']").on("change", function(){ 
    $("form#data").unbind('submit'); 
    $("form#data").submit(); 
}); 

當您綁定的事件(即這裏是提交)發生了一次又一次。在頁面加載的時候,你已經綁定了提交事件,並且你在輸入改變事件上綁定了相同的代碼,所以代碼將執行兩次並且將兩次上傳文件。

+0

但是取消綁定提交帶我直接執行提交操作 – AngularAngularAngular 2014-11-14 13:15:33

+0

更新後嘗試上面的代碼:) – 2014-11-14 13:18:28

+0

然後我添加了兩個函數,如下$(document).on(「change」,「#imageone」,function() {(「form#dataone」)。submit(); });但它不是調用第二個函數 – AngularAngularAngular 2014-11-14 13:24:17