文件在ajax页面上传

时间:2011-12-03 04:15:19

标签: php javascript ajax xmlhttprequest

我正在尝试在ajax结果页面上进行文件上传。

main.php文件是一个基本的ajax代码,如下所示:

<html>
 <head>
<script type="text/javascript">
    function loadXMLDoc() {
        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");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "file.php", true);
        xmlhttp.send();
    }
</script>    
 </head>
 <body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onClick="loadXMLDoc()">Change Content</button>

</body>
</html>

文件上传格式file.php如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="fileupload.php">
  <p>
    <label for="file"></label>
    <input type="file" name="file" id="file" />
  </p>
  <p>
    <input type="submit" name="submit" id="submit" value="Submit" />
  </p>
</form>
</body>
</html>

我有第3个文件处理文件上传fileupload.php

<?php
$file_fullname= $_FILES['file']['name'];
$file_ext1 = pathinfo($file_fullname, PATHINFO_EXTENSION);
$file_ext = ".".$file_ext1;
$file_name = pathinfo($file_fullname,PATHINFO_BASENAME);
$temp_name = str_replace($file_ext,'',$file_fullname);
$new_file_name = md5($temp_name . $dt);
echo $path= "upload/".$new_file_name . $file_ext;
$photo = $new_file_name . "" . $file_ext;
echo "<BR>";

   if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists($path))
      {
      echo $path . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"], $path);
      echo "Stored in: " . $path;
      }
    }
?>

当我将表单发布到fileupload.php

时,页面工作正常

但是当我使用ajax代码将fileupload.php的内容移动到file.php中时。好像文件上传过程没有运行。更新后的代码file2.php如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
    <script type="text/javascript">
    function fileup()
    {
    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");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","file.php",true);
    xmlhttp.send();
    }
    </script>

<?php
$file_fullname= $_FILES['file']['name'];
$file_ext1 = pathinfo($file_fullname, PATHINFO_EXTENSION);
$file_ext = ".".$file_ext1;
$file_name = pathinfo($file_fullname,PATHINFO_BASENAME);
$temp_name = str_replace($file_ext,'',$file_fullname);
$new_file_name = md5($temp_name . $dt);
echo $path= "upload/".$new_file_name . $file_ext;
$photo = $new_file_name . "" . $file_ext;
echo "<BR>";

   if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists($path))
      {
      echo $path . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"], $path);
      echo "Stored in: " . $path;
      }
    }
?>
</head>

<body>
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="fileupload.php">
  <p>
    <label for="file"></label>
    <input type="file" name="file" id="file" />
  </p>
  <p>
    <button type="button" onClick="fileup()">Upload</button>
  </p>
</form>
</body>
</html>

能建议吗?我只是想在ajax结果部分完成文件上传,因此无需刷新整个页面。

谢谢!

2 个答案:

答案 0 :(得分:2)

从历史上看,作为安全预防措施,JavaScript无法访问<input type="file">元素的值。

File API已定义为与JavaScript中的文件交互提供一些支持,并且有一些支持 - http://caniuse.com/fileapi

但是,如果要考虑与旧版浏览器的兼容性,则无法使用Ajax上传文件。

答案 1 :(得分:0)

我建议你使用这个插件。我在项目中使用它来进行ajax上传。

http://jquery.malsup.com/form/#file-upload

此插件用于上传,使用表单并以多部分方式发送数据。您可以看到示例代码:

<form id="uploadForm" action="files.php" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                File: <input type="file" name="file">
                Return Type: <select id="uploadResponseType" name="mimetype">
                    <option value="html">html</option>
                    <option value="json">json</option>
                    <option value="script">script</option>
                    <option value="xml">xml</option>
                </select>
                <input type="submit" value="Submit">
            </form>

这是将您的表单转换为ajax上传的代码:

 $('#uploadForm').ajaxForm({
        beforeSubmit: function(a,f,o) {
            o.dataType = $('#uploadResponseType')[0].value;
            $('#uploadOutput').html('Submitting...');
        },
        success: function(data) {
            var $out = $('#uploadOutput');
            $out.html('Form success handler received: <strong>' + typeof data + '</strong>');
            if (typeof data == 'object' && data.nodeType)
                data = elementToString(data.documentElement, true);
            else if (typeof data == 'object')
                data = objToString(data);
            $out.append('<div><pre>'+ data +'</pre></div>');
        }
    });