2015-10-07 169 views
0

我正在嘗試使用Ajax進行圖像預覽功能。使用Ajax進行圖像預覽:返回損壞的圖像圖標

當我嘗試,我有一些問題彈出:

  1. 當阿賈克斯不得不拼命地跑,沒有圖像本身已經被上傳到服務器?或者只是一個數組已發送,包括字符串名稱,類型,大小,tmp_name?
  2. 下面的代碼會返回一個破碎的圖標圖標。

我曾嘗試:

HTML文件:

<script type="text/javascript" src="/script/googleapis.js"></script> 


<input multiple type="file" id="myFile" size="50"> 

<div id="sub">submit</div> 

<div id="testtest"></div> 



<script> 
$("#sub").click(function(){ 
    // get the file objects 
    var files = $("#myFile")[0].files, 
     data = new FormData; 

    for (var i = 0; i < files.length; i++){ 
     //test if the files[i] has the file objects 
     console.log(files[i]); 
     //post objects to another php file 
     data.append('img[]', files[i]); 
    } 

    $.ajax({ 
     url: "testphp.php", 
     type: "POST", 
     data: data, 
     contentType: false, 
     processData: false, 
     success: function(result){ 
      $("#testtest").html(result); 
     } 
    }); 
}); 

</script> 

PHP文件(test.php的)

<?php 

$file_name=$_FILES['img']['name'][0]; 
$file_tmp=$_FILES['img']['tmp_name'][0]; 
var_dump($file_tmp); // for test if the variable has been post successfully 
echo "<img src='".$file_tmp."'>"; 
?> 
+0

文件需要一個有效的加密類型 –

+0

你能不能解釋一下? –

+0

您可以嘗試將「FormData」對象直接傳遞給PHP腳本,而不是將任何內容附加到它。然後在PHP腳本中迭代圖像數組。 –

回答

0

這裏在圖像預覽添加https://jsfiddle.net/bhx0s2dh/2/

它是不是很難使用filereader。

HTML

<input id="image" type="file" multiple></input> 
<div id="image-preview"></div> 

的Javascript

$('#image').change(function() { //whenever the input changes 
    PreviewImage(this); 
}); 

function PreviewImage(source) { 
    if (!! window.FileReader) { //check if browser supports file reader 
     $('#image-preview').html(''); //wipe the preview container 
     var files = source.files; //get the file from the input 
     for (var i = 0; i < files.length; i++) { 
      var file = files[i].name; //get the file name *if you need it* 
      $reader = new FileReader(); //initialize file reader 
      $reader.readAsDataURL(files[i]); //read the file 
      $reader.onload = function (e) { //load the result 
       $('#image-preview').append('<div class="images"><img src="' + e.target.result + '" ></div>'); 
        //e.target.result is the src 
      } 
     } 
    } 
} 

CSS

.images { 
    float:left; 
} 
.images img { 
    width:auto; 
    height:auto; 
    max-width:200px; 
    max-height:200px; 
} 
+0

謝謝你的作品完美!當貼到PHP文件的文件對象,如文件名 「07.png」 尺寸:33022 lastModifiedDate:日期 名: 「07.png」 大小:33022 類型: 「圖像/ PNG」 webkitRelativePath: 「」 文件本身(有很多字節)是否也被傳送到服務器端?或者只有上述屬性值對已經轉移。 我不清楚文件對象後的內容。 –

+0

它不轉移到服務器。這繞過了服務器。這樣做可以讓瀏覽器從客戶端的本地驅動器顯示圖像。 – stanley1943