使用Ajax预览图像:返回一个损坏的图像图标


Image preview using Ajax:returns a broken image icon

我正在尝试使用Ajax制作图像预览功能。

当我尝试的时候,我有一些问题弹出:

    当Ajax运行时,图像本身是否已经上传到服务器?还是只是发送了一个数组,包含字符串名称,类型,大小,tmp_name?
  1. 下面的代码返回一个损坏的图像图标。

I have try:

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."'>";
?>

在这里添加图像预览https://jsfiddle.net/bhx0s2dh/2/

使用文件阅读器并不难。

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;
}