AJAX(jQuery的)最简单的版本上载只有一个文件 [英] The simplest version of ajax (jQuery) to upload just one file

查看:127
本文介绍了AJAX(jQuery的)最简单的版本上载只有一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只希望用户选择一个文件,它会自动将其下载到我的服务器。我不需要任何更多的功能。什么是最简单,最reliabe(也许你用过吗?)插件来做到这一点?尝试 https://github.com/valums/file-uploader ,但不能把它工作

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.

推荐答案

这是一个网页,如:upload.html

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> 

这是调用PHP像这样:upload..php

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

这篇关于AJAX(jQuery的)最简单的版本上载只有一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆