使用Ajax预览图像:返回一个损坏的图像图标
Image preview using Ajax:returns a broken image icon
我正在尝试使用Ajax制作图像预览功能。
当我尝试的时候,我有一些问题弹出:
- 当Ajax运行时,图像本身是否已经上传到服务器?还是只是发送了一个数组,包含字符串名称,类型,大小,tmp_name?
- 下面的代码返回一个损坏的图像图标。
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;
}
相关文章:
- 如何在鼠标悬停时在另一个图像上滑动图像.
- 如何将多个画布保存为一个图像
- 是否可以仅通过jQuery将图像替换为用户动态选择的另一个图像
- Javascript/jQuery压缩一个图像正确的评论帖子,并使用Ajax Laravel 5.2保存到控制器中
- 如何在设定的时间间隔内一次只显示一个图像
- 如何在另一个html文件的框架中包含图像
- 循环以检查数组中的最后一个图像
- 下载Div&画布为一个图像
- 使用D3.js和GeoJson在地图上的某些坐标上设置一个小图像
- 当页面包含指向一个图像的多个链接时,fancyBox会复制缩略图辅助图像
- PNG图像被覆盖,但每个图像都有一个链接可以更改,每次一个-Javascript/jQuery/CSS
- 如何从 javascript 中可能具有一个或多个图像的字符串中仅获取图像名称
- 在引导程序旋转木马中显示下一个图像
- 拉斐尔用一个图像填满了这个圆圈
- 一个javascript实现base64图像编码并将结果写入文本文件
- 当我点击MVC视图中的图像时,如何打开另一个页面
- 创建,显示图像作为背景图像一个接一个- JavaScript
- 添加图像一个接一个的元素点击
- 将图像一个叠在另一个上面
- 将图像一个堆叠到另一个(javascript)