美文网首页Coding。
Html5以及jQuery实现本地图片上传前的预览

Html5以及jQuery实现本地图片上传前的预览

作者: iLevitate | 来源:发表于2017-08-02 09:12 被阅读163次
<!DOCTYPE html>  
<html>  
<head>  
<title>HTML5上传图片预览</title>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<script src="http://www.codefans.net/ajaxjs/jquery-1.6.2.min.js"></script>  
</head>  
<body>  
<h3>请选择图片文件:</h3>  
<form name="form0" id="form0" >  
<!-- 这里特别说一下这个 multiple="multiple" 添加上这个之后可以一次选择多个文件进行上传,是 html5 的新属性-->  
<input type="file" name="file0" id="file0" multiple="multiple/formdata" />
<br>
<img src="" id="img0" >  
</form>  
<script>    
$("#file0").change(function(){  
  // getObjectURL是自定义的函数
  // this.files[0]代表的是选择的文件资源的第一个,因为上面写了 multiple="multiple" 就表示上传文件可能不止一个  
  // ,但是这里只读取第一个   
  var objUrl = getObjectURL(this.files[0]) ;  
  // console.log("objUrl = "+objUrl) ;    //打印出来看一下下
  if (objUrl) {  
    // 在这里修改图片的地址属性  
    $("#img0").attr("src", objUrl) ;  
  }  
}) ;  
//建立一個可存取到該file的url  
function getObjectURL(file) {  
  var url = null ;   
  // 下面函数执行的效果是一样的,只是需要针对不同的浏览器执行不同的 js 函数而已  
  if (window.createObjectURL!=undefined) { // basic  
    url = window.createObjectURL(file) ;  
  } else if (window.URL!=undefined) { // mozilla(firefox)  
    url = window.URL.createObjectURL(file) ;  
  } else if (window.webkitURL!=undefined) { // webkit or chrome  
    url = window.webkitURL.createObjectURL(file) ;  
  }  
  return url ;  
}  
</script>  
</body>  
</html>  



<?php 
$file = $_FILES['file'];//得到传输的数据
        //得到文件名称
        $name = $file['name'];
        $type = strtolower(substr($name, strrpos($name, '.') + 1)); //得到文件类型,并且都转化成小写
        $allow_type = array('jpg', 'jpeg', 'gif', 'png'); //定义允许上传的类型
        //判断文件类型是否被允许上传
        if (!in_array($type, $allow_type)) {
            //如果不被允许,则直接停止程序运行
            return "Defined";
        }

        //判断上传文件夹,不存在则创建
        $date = date("Ym");
        $path = getcwd() . '/uploads/images/' . $date;
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        //生成新文件名
        $file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $type;
        //移动文件到相应的文件夹
        if (move_uploaded_file($file['tmp_name'], $path . "/" . $file_name)) {
            return "Successfully!";
        } else {
            return "Failed!";
        }

相关文章

网友评论

    本文标题:Html5以及jQuery实现本地图片上传前的预览

    本文链接:https://www.haomeiwen.com/subject/ldkelxtx.html