jQuery AJAX - 使用FormData上传文件

时间:2014-01-18 11:19:02

标签: javascript php jquery ajax upload

我正在尝试使用WordPress管理中的AJAX上传文件。这是我的代码:

   <script>
        $(document).ready(function()
            {
                $("#upload_app").click(function(e)
                {
                    event.stopPropagation();
                            event.preventDefault();

                    var data = new FormData();

                    aaa = document.getElementById("path_to_file");

                    alert(aaa.files[0]);

                    data.append("newFile",aaa.files[0]);

                    alert(data["newFile"]);

                    $.ajax({
                        url: "'.get_site_url().'/wp-content/plugins/move_and_match/upload_file.php",
                        type: "POST",
                        data: data,
                        cache: false,
                        dataType: "json",
                        processData: false,
                        contentType: false,
                        success: uploadDone,
                        error: uploadFailed
                    });
                });
            });

            function uploadDone(returns)
            {
                alert(returns);
                $("#uploadFileMetaBox p").text("Successfull.");
            }

            function uploadFailed(returns)
            {
                alert(returns);
                $("#uploadFileMetaBox p").text("Problem occured.");
            }
</script>

AJAX访问PHP脚本没有问题,但没有发送文件。如您所见,我向脚本添加了一些警报。第一个alert(aaa.files[0]);没有问题,但第二个(当aaa的值应插入FormData对象时)表示值为undefined

这是jsfiddle

我做得不好?

感谢您的回答。

2 个答案:

答案 0 :(得分:0)

哦,我知道你想用javascript(AJAX)发送文件

因为如果安全性无法访问使用javascript浏览按钮添加的文件和文件路径。据我所知,你应该通过表格发送。

我知道的方法是使用隐藏的<iframe> <form>

  
      
  1. 您的身体中应该有一个HTML <iframe>元素,可以使用javascript
  2. 创建它   
  3. 想要在活动中做AJAX事吗?比如onclick上传按钮或onchange浏览文件输入所以你应该这样做(当你想提交表格时调用ajaxUpload(iframeObj))
  4.   
  5. 'ajaxUpload()'函数会将表单的目标设置为iframe,并且会提交您的表单。
  6.   
  7. 我们为iframe的onload添加了一个监听器,所以当表单上传并且结果来自服务器时,iframeReady函数将被调用,然后将获取iframe的内容(这里是上传图像的url)   5.(注意你在PHP文件中发送的输出应该用HTML和body标签覆盖,因为我们可以得到iframe的正文内容)
  8.   

整个想法就是这个,我已经测试过,如果还有任何问题请告诉我。

的javascript:

$(document).ready(function(){

    function ajaxUpload(mf){
      $(mf).prop('target',#hiddenIframe');
      $(mf).submit();
      $('#hiddenIframe').on('load',function(){
        IframeReady();
      }
    }

    function getFrameContents(iFrame){
       var iFrameBody;
       if ( iFrame.contentDocument ) 
       { // FF
         iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
       }
       else if ( iFrame.contentWindow ) 
       { // IE
         iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
       }
        return iFrameBody.innerHTML;
    }

    function IframeReady(){
      var miframe=$('#hiddenIframe');
      var result;
      var $odiv=$('#result');
      result=getFrameContents(miframe);
      $odiv.html(result);
    }
});

HTML:

<iframe name="hiddenIframe" id="hiddenIframe" style="width:0;height:0;display:none;"></iframe>
<div class="result" id="resultBox">Result will be displayed here.</div>
<form action="/saveImage_ajax.php" method="POST" enctype="form/multipart">
Please upload your image: <input type="file" name="mimg" /><br/>
<input type="button" value="upload" onclick="ajaxUpload(this.parentNode)" />
</form>

PHP文件(saveImage_ajax.php)(或任何你想要的东西。)

<?php

// do some stuff to save Image In a location.

$ret= json_encode(array('status'=>'ok','src'=>'the destination of image file'));

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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>
<?php
echo $ret;
?>
</body>
</html>

答案 1 :(得分:0)

  • FormData对象不会公开其任何项目,因此没有data["newFile"]
  • 你的网址非常不稳定。 '.get_site_url().'/wp-content/plugins/move_and_match/upload_file.php不是想要的网址

    url: "<?php echo get_site_url() ?>/wp-content/plugins/move_and_match/upload_file.php",
    
  • 如果您的事件参数为event,则使用e将会废弃未设置全局 event对象的浏览器。您应该将其重命名为event。 function(event){
相关问题