使用jquery ajax异步提交图片
<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="black" name="apple-mobile-web-app-status-bar-style" /> <meta content="telephone=no" name="format-detection" /> <title>测试</title> <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="js/ajax.js"></script> </head> <body> <div > <img src="images/user.png" id="up-img"> <input type="file" name="img" id="up-file"> </div> </body> </html>
<script type="text/javascript">
$(document).on(‘change‘, ‘#up-file‘, function(event) {
var file = $(‘#up-file‘)[0].files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024 * 5){
alert("请上传小于1M的图片");
return false;
}
else {
if (file.type == ‘image/jpeg‘ || file.type == ‘image/png‘ || file.type == ‘image/gif‘) {
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + ‘KB‘;
}
else{
alert("请上传jpg,png,gif格式的图片");
return false;
};
}
var imgtype=file.type;//获取图片类型,也可以在服务器获取
var reader = new FileReader();//
reader.onload = function ( event ) {
var img = event.target.result;
$(‘#up-img‘).attr(‘src‘,img);//预览图片
var data={img:img,imgtype:imgtype,cmd:‘upimg‘};
$.ajax({
type:‘POST‘,
data:data,
dataType:‘json‘,
url:‘ajax.php‘,
success:function(msg){
if(msg == 0) {
alert("上传成功");
location.href=‘login.php‘;
}
}
})
};
}
reader.readAsDataURL(file);//转为base64编码
});
</script><?php
$base64=POSTS("img");
$typeimg=POSTS("imgtype");
$typeimg=substr($typeimg, 6); //获取图片后缀
$base64 = substr($base64,22);//截图实际信息
$filename = "/upload/fnks_img/";//设置保存目录
$img = base64_decode($base64);//将获取的编码字符串解码
$adtime=date("YmdHis").rand(10000,99999);//重新命名
$savefile = file_put_contents(‘./upload/‘.$adtime.‘.‘.$typeimg, $img);//将转好的图片保存到指定目录下
$path=‘./upload/‘.$adtime.‘.‘.$typeimg;//文件路径本文出自 “IT技术” 博客,请务必保留此出处http://linuxubuntu.blog.51cto.com/4964714/1785563
原文地址:http://linuxubuntu.blog.51cto.com/4964714/1785563