我正在嘗試使用Ajax進行圖像預覽功能。使用Ajax進行圖像預覽:返回損壞的圖像圖標
當我嘗試,我有一些問題彈出:
- 當阿賈克斯不得不拼命地跑,沒有圖像本身已經被上傳到服務器?或者只是一個數組已發送,包括字符串名稱,類型,大小,tmp_name?
- 下面的代碼會返回一個破碎的圖標圖標。
我曾嘗試:
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."'>";
?>
文件需要一個有效的加密類型 –
你能不能解釋一下? –
您可以嘗試將「FormData」對象直接傳遞給PHP腳本,而不是將任何內容附加到它。然後在PHP腳本中迭代圖像數組。 –