简体   繁体   中英

The simplest version of ajax (jQuery) to upload just one file

I just want user to select a file and it would automatically download it to my server. I don't need no more features. What is the simplest and most reliabe (maybe you used it?) plugin to do that? Tried https://github.com/valums/file-uploader , but couldn't get it to work.

from a web page such as: upload.html

<html>
<head>
<script type="text/javascript">
    function uploadFile(){
        var xmlhttp;
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        var formElement = document.getElementById("upload");
        var formData= new FormData(formElement);
        xmlhttp.open("post","upload.php",false);
        xmlhttp.send(formData);
        var counter = 0;
        while (xmlhttp.readyState != 4){
            counter = counter + 1;
        }
        var errorCondition =  xmlhttp.responseText;
        if(errorCondition == "success"){
            alert("File uploaded successfully");
        }
        else{
            alert("Error: "+errorCondition);
        }
    }
</script>

</head>
<body>

<form id="upload" action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="button" name="submit" value="Submit" onclick="uploadFile();" />
</form>

</body>
</html> 

that calls php such as this: upload..php

<?php
if ($_FILES["file"]["error"] > 0)
    {
    echo ($_FILES["file"]["error"]);
    }
else
    {
    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "success";
      }
    }
?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM