2013-04-06 24 views
0

我有一個允許用戶上傳圖片的jQuery函數。誠然,我對jQuery知之甚少,但我需要能夠稍微更改此代碼。目前它會拋出一個錯誤,如果一個文件不是圖像被使用,但我希望它拋出一個錯誤是一個文件不是JPG,JPG,JPEG或JPEG。如何將jQuery代碼改爲只允許jpg文件

我不確定需要多少原始代碼,但這是進行過濾的部分。

$(document).ready(function() { 

    // Makes sure the dataTransfer information is sent when we 
    // Drop the item in the drop box. 
    jQuery.event.props.push('dataTransfer'); 

    var z = -40; 
    // The number of images to display 
    var maxFiles = 5; 
    var errMessage = 0; 

    // Get all of the data URIs and put them in an array 
    var dataArray = []; 

    // Bind the drop event to the dropzone. 
    $('#drop-files').bind('drop', function(e) { 

     // Stop the default action, which is to redirect the page 
     // To the dropped file 

     var files = e.dataTransfer.files; 
     var ext = $('#drop-files').val().split('.').pop().toLowerCase(); 


     // Show the upload holder 
     $('#uploaded-holder').show(); 

     // For each file 
     $.each(files, function(index, file) { 
      // Some error messaging 
      if (!files[index].type.match('image.*')) { 

       if(errMessage == 0) { 
        $('#drop-files').html('Only jpg files are allowed'); 

       } 

       return false; 
      } 

      // Check length of the total image elements 

      if($('#dropped-files > .image').length < maxFiles) { 
       // Change position of the upload button so it is centered 
       var imageWidths = ((220 + (40 * $('#dropped-files > .image').length))/2) - 20; 
       $('#upload-button').css({'left' : imageWidths+'px', 'display' : 'block'}); 
      } 

      // Start a new instance of FileReader 
      var fileReader = new FileReader(); 

       // When the filereader loads initiate a function 
       fileReader.onload = (function(file) { 

        return function(e) { 

         // Push the data URI into an array 
         dataArray.push({name : file.name, value : this.result}); 

         // Move each image 40 more pixels across 
         z = z+40; 
         var image = this.result; 


         // Just some grammatical adjustments 
         if(dataArray.length == 1) { 
          $('#upload-button span').html("1 file to be uploaded"); 
         } else { 
          $('#upload-button span').html(dataArray.length+" files to be uploaded"); 
         } 
         // Place extra files in a list 
         if($('#dropped-files > .image').length < maxFiles) { 
          // Place the image inside the dropzone 
          $('#dropped-files').append('<div class="image" style="left: '+z+'px; background: url('+image+'); background-size: cover;"> </div>'); 
         } 
         else { 

          $('#extra-files .number').html('+'+($('#file-list li').length + 1)); 
          // Show the extra files dialogue 
          $('#extra-files').show(); 

          // Start adding the file name to the file list 
          $('#extra-files #file-list ul').append('<li>'+file.name+'</li>'); 

         } 
        }; 

       })(files[index]); 

      // For data URI purposes 
      fileReader.readAsDataURL(file); 

     }); 


    }); 

    function restartFiles() { 

     // This is to set the loading bar back to its default state 
     $('#loading-bar .loading-color').css({'width' : '0%'}); 
     $('#loading').css({'display' : 'none'}); 
     $('#loading-content').html(' '); 
     // -------------------------------------------------------- 

     // We need to remove all the images and li elements as 
     // appropriate. We'll also make the upload button disappear 

     $('#upload-button').hide(); 
     $('#dropped-files > .image').remove(); 
     $('#extra-files #file-list li').remove(); 
     $('#extra-files').hide(); 
     $('#uploaded-holder').hide(); 

     // And finally, empty the array/set z to -40 
     dataArray.length = 0; 
     z = -40; 

     return false; 
    } 

    $('#upload-button .upload').click(function() { 

     $("#loading").show(); 
     var totalPercent = 100/dataArray.length; 
     var x = 0; 
     var y = 0; 

     $('#loading-content').html('Uploading '+dataArray[0].name); 

     $.each(dataArray, function(index, file) { 

      $.post('upload.php', dataArray[index], function(data) { 

       var fileName = dataArray[index].name; 
       ++x; 

       // Change the bar to represent how much has loaded 
       $('#loading-bar .loading-color').css({'width' : totalPercent*(x)+'%'}); 

       if(totalPercent*(x) == 100) { 
        // Show the upload is complete 
        $('#loading-content').html('Uploading Complete!'); 
        window.location = "http://www.dentaldigs.co.uk/upload_success.php"; 

        // Reset everything when the loading is completed 
        setTimeout(restartFiles, 500); 

       } else if(totalPercent*(x) < 100) { 

        // Show that the files are uploading 
        $('#loading-content').html('Uploading '+fileName); 

       } 

       // Show a message showing the file URL. 
       var dataSplit = data.split(':'); 
       if(dataSplit[1] == 'upload successful') { 
        var realData = '<li><a href="images/'+dataSplit[0]+'">'+fileName+'</a> '+dataSplit[1]+'</li>'; 

        $('#uploaded-files').append('<li><a href="images/'+dataSplit[0]+'">'+fileName+'</a> '+dataSplit[1]+'</li>'); 

        // Add things to local storage 
        if(window.localStorage.length == 0) { 
         y = 0; 
        } else { 
         y = window.localStorage.length; 
        } 

        window.localStorage.setItem(y, realData); 

       } else { 
        $('#uploaded-files').append('<li><a href="images/'+data+'. File Name: '+dataArray[index].name+'</li>'); 
       } 

      }); 
     }); 

     return false; 
    }); 

    // Just some styling for the drop file container. 
    $('#drop-files').bind('dragenter', function() { 
     $(this).css({'box-shadow' : 'inset 0px 0px 20px rgba(0, 0, 0, 0.1)', 'border' : '4px dashed #B3C234'}); 
     return false; 
    }); 



    $('#drop-files').bind('drop', function() { 
     $(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0, 0, 0, 0.1)'}); 
     return false; 
    }); 

    // Let them know that they aren’t in the correct dragenter zone 
    $('#drop-files').bind('dragleave', function() { 
    $(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0,0,0,0.2)'}); 
    return false; 
    }); 

    // For the file list 
    $('#extra-files .number').toggle(function() { 
     $('#file-list').show(); 
    }, function() { 
     $('#file-list').hide(); 
    }); 

    $('#dropped-files #upload-button .delete').click(restartFiles); 

    // Append the localstorage the the uploaded files section 
    if(window.localStorage.length > 0) { 
     $('#uploaded-files').show(); 
     for (var t = 0; t < window.localStorage.length; t++) { 
      var key = window.localStorage.key(t); 
      var value = window.localStorage[key]; 
      // Append the list items 
      if(value != undefined || value != '') { 
       $('#uploaded-files').append(value); 
      } 
     } 
    } else { 
     $('#uploaded-files').hide(); 
    } 
}); 

目前,這將使任何圖像類型,我需要它的,只允許JPG格式,JPG,JPEG和JPEG

+0

我們需要的代碼的其餘部分,或者e.dataTransfer'的'內容。在'var files = e.dataTransfer.files'之後,你可以添加'console.log(files);'並將結果粘貼到你的問題中? – 2013-04-06 17:30:57

+0

好吧,現在就這樣做 – tatty27 2013-04-06 17:34:51

+2

還記得在服務器端做一個同類測試。 – Mchl 2013-04-06 17:38:33

回答

1

改變這一行:

if (!files[index].type.match('image.*')) { 

到這一點:

if (!(files[index].type.match("image.*") && files[index].name.match(/\.(jpg|jpeg)$/i))) { 

它應該再工作。

+0

嗨,謝謝你,但它仍然允許非jpg或JP​​G文件上傳。有沒有辦法可以限制上傳到某些文件類型,如jpg和JPG? – tatty27 2013-04-06 17:55:35

+0

編輯代碼。 – 2013-04-06 17:56:28

+0

謝謝,不得不做一個小小的修改,所以行實際上讀取if(!(files [index] .name.match(/ \。(jpg | jpeg)$/i))){。感謝您的幫助 – tatty27 2013-04-06 18:00:30

0

也許嘗試正則表達式?

$.each(files, function(index, file) { 
      // Some error messaging 
      if (!files[index].type.match('image.*')) { 
        errMessage = 1; 
        var pattern = /(\.(?:jpg|jpeg|JPG|JPEG))$/gm; 

        if (!file.name.match(pattern)){ 
        errMessage = 0 
        } 
       if(errMessage == 0) { 
        $('#drop-files').html('Only jpg files are allowed'); 

       } 

       return false; 
      } 
} 

編輯:代碼是未經測試的。但希望能給出一個想法我的意思。另外,假設你得到一個文件對象中的「文件」

+0

嗨,恐怕它仍然允許.png被上傳 – tatty27 2013-04-06 17:39:41

+0

對不起,更新了答案 – Stpn 2013-04-06 17:55:26

+0

謝謝你,它仍然沒有工作,我懷疑type.match參數阻止它的工作方式與它做的一樣在Sebastien Renauld的解決方案中。感謝您的幫助,雖然 – tatty27 2013-04-06 18:02:29

1

從文件數組中刪除不需要的文件怎麼辦?

if (!files[index].type.match('image.*')) { 

      if(errMessage == 0) { 
       $('#drop-files').html('Only jpg files are allowed'); 

      } 

      return false; 
     } 
     /* Remove file from the array if it doesnt match jpg | jpeg */ 
     else if ((files[index].name.match(/.+(jpg|jpeg)$/)){ 
      files.splice(index, 1); 
      return; 
     } 
     .... 

如果文件不是他們不會被讀取文件列表/上傳

+0

這是一個絕妙的主意,唯一的問題是,如果(如果...出現錯誤 – tatty27 2013-04-06 18:10:51

+0

),那麼Dreamweaver會將其他行標記爲else if else條件中存在額外的內容,上面的代碼現在 – 2013-04-07 09:05:58

+0

非常棒,非常感謝 – tatty27 2013-04-07 21:27:50