欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php+js实现异步图片上传实例分享

程序员文章站 2023-10-23 18:58:10
upload.php 复制代码 代码如下:

upload.php

复制代码 代码如下:

<?php
if(isset($_files["myfile"]))
{
$ret = array();
$uploaddir = 'images'.directory_separator.date("ymd").directory_separator;
$dir = dirname(__file__).directory_separator.$uploaddir;
file_exists($dir) || (mkdir($dir,0777,true) && chmod($dir,0777));
if(!is_array($_files["myfile"]["name"])) //single file
{
$filename = time().uniqid().'.'.pathinfo($_files["myfile"]["name"])['extension'];
move_uploaded_file($_files["myfile"]["tmp_name"],$dir.$filename);
$ret['file'] = directory_separator.$uploaddir.$filename;
}
echo json_encode($ret);
}

?>

index.html

复制代码 代码如下:

<!doctype html>
<html>
<head>
    <title>html5 ajax 上传文件</title>
    <meta charset="utf-8">

<script type="text/javascript">


    var xhr;
    function createxmlhttprequest()
    {
        if(window.activexobject)
        {
            xhr = new activexobject("microsoft.xmlhttp");
        }
        else if(window.xmlhttprequest)
        {
            xhr = new xmlhttprequest();
        }
    }


    function upladfile()
    {
        var fileobj = document.getelementbyid("file").files[0];
        var filecontroller = 'upload.php';
        var form = new formdata();
        form.append("myfile", fileobj);
        createxmlhttprequest();
        xhr.onreadystatechange = handlestatechange;
        xhr.open("post", filecontroller, true);
        xhr.send(form);
    }


    function handlestatechange()
    {
        if(xhr.readystate == 4)
        {
            if (xhr.status == 200 || xhr.status == 0)
            {
                var result = xhr.responsetext;
                var json = eval("(" + result + ")");
                alert('图片链接:\n'+json.file);
            }
        }
    }


</script>


<style>
    .txt{ height:28px; border:1px solid #cdcdcd; width:670px;}
    .mybtn{ background-color:#fff; line-height:14px;vertical-align:middle;border:1px solid #cdcdcd;height:30px; width:70px;}
    .file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px }
</style>
</head>


<body>

<div class="form-group">
    <label class="control-label">图片</label>
    <br/>
    <input type='text' name='textfield' id='textfield' class='txt' />
    <span onclick="file.click()"  class="mybtn">浏览...</span>
    <input type="file" name="file" class="file" id="file" size="28" onchange="document.getelementbyid('textfield').value=this.value" />
    <span onclick="upladfile()" class="mybtn">上传</span>
</div>

</body>


</html>