php+ajax Example of Picture File Upload Function

  • 2021-06-29 10:36:40
  • OfStack

There are several commonly used asynchronous file upload functions, such as using the iframe framework, the ajax function effect, and the flash+php function. Below are some examples of the functions of ajax and iframe for asynchronous file upload.

Method 1, file upload using jquery ajaxfileupload.js

In fact, it is to achieve file upload without refresh.The IFRAME file upload principle can be used.
Essentially when you upload a file with PHP.Only $_can be usedThe FILES form, but if we only take JS for one, for example < input id='img' type='file' > ... document.getElementById ('img'). value or $('#img') in the form of jquery cannot actually be uploaded (but many people do, and I did at the beginning).
But what about the so-called asynchronous upload function?You can only use a third-party component or write one yourself (embedding an IFRAME in a web page).However, if you are considering development time, it is recommended to use a third party where there is a good Ajax file upload component for jQuery,'ajaxfileupload.js', whose download address is: //img.jbzj.com/file_images/article/201306/js/ajaxfileupload.js

Process:

(1) Code for front-end file: test.php

<script type="text/javascript" src="jquery.js"></script> 
 <script type="text/javascript" src="ajaxfileupload.js"></script>
 <script type="text/javascript">
 function ajaxFileUpload()
{
$.ajaxFileUpload
(
  {
 url:'doajaxfileupload.php', // Your server for uploading files 
 secureuri:false,
 fileElementId:'img',
 dataType: 'json',
 success: function (data)
 {
alert(data.file_infor);
 }
 }
 )
  return false;
  } 
  </script>
 Corresponding HTML For: 
  <input id="img" type="file" size="45" name="img" class="input">
  <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>

This completes the client.

(2) doajaxfileupload.php on the server side

Here, you can save it for the sake of checking if it's actually passed in.

$file_infor = var_export($_FILES,true);
 file_put_contents("d:file_infor.php".$file_infor);

So you call the newly generated file_When you read the infor.php file, you saw familiar information again:

array(
 'name'=>'lamp.jpg',
 'type'=>'image/pjpeg',
 'tmp_name'=>'c:windowstempphpFA.tmp',
 'error'=>0,
 'size'=>3127
)

Of course, the real processing is like this:

<?php
  $upFilePath = "d:/";
  $ok=@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath);
if($ok === FALSE){
 echo json_encode('file_infor'=>' Upload failed ');
}else{
 echo json_encode('file_infor'=>' Upload Successful ');
}
?>

Method 2, upload pictures using the iframe framework

The html code is as follows:

<div class="frm">
  <form name="uploadFrom" id="uploadFrom" action="upload.php" method="post"  target="tarframe" enctype="multipart/form-data">
   <input type="file" id="upload_file" name="upfile">
  </form>
  <iframe src=""  width="0" height="0" style="display:none;" name="tarframe"></iframe>
 </div>
 <div id="msg">
 </div>

index.js file:

$(function(){
 $("#upload_file").change(function(){
   $("#uploadFrom").submit();
 });
});
function stopSend(str){
 var im="<img src='upload/images/"+str+"'>";
 $("#msg").append(im);
}


upload.php file:

<?php
 $file=$_FILES['upfile'];
 $name=rand(0,500000).dechex(rand(0,10000)).".jpg";
 move_uploaded_file($file['tmp_name'],"upload/images/".$name);
// call iframe Parent window js  function 
 echo "<script>parent.stopSend('$name')</script>";
?>

Method 3, upload native ajax file


<!DOCTYPE html>
<html>
<head>
    <title>Html5 Ajax  Upload Files </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(' pictures linking :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"> picture </label>
    <br/>
    <input type='text' name='textfield' id='textfield' class='txt' />
    <span onclick="file.click()"  class="mybtn"> browse ...</span>
    <input type="file" name="file" class="file" id="file" size="28" onchange="document.getElementById('textfield').value=this.value" />
    <span onclick="UpladFile()" class="mybtn"> upload </span>
</div>
</body>
</html>

php code:


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


Related articles: