doucheng7534 2014-01-18 11:19
浏览 103

jQuery AJAX - 使用FormData上传文件

I am trying to upload file using AJAX in WordPress administration. Here is my code:

   <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 access PHP script without problems but no files are sent. As you can see I added some alerts to the script. First one alert(aaa.files[0]); works without problems but the second one (when the value of aaa should be inserted into FormData object) says that the value is undefined.

Here is jsfiddle

What am I doing bad?

Thanks for answers.

  • 写回答

2条回答 默认 最新

  • duanjie5570 2014-01-18 11:41
    关注

    Oh I got it you want to send files using javascript (AJAX)

    because if security you can't access to files and paths of files added by browse button with javascript. And as I know you should send it by a form.

    And the way that I know is to use a hidden <iframe> <form>:

    1. You should have a HTML <iframe> element in your body of create it with javascript
    2. Want to do the AJAX thing en an event right? like onclick of upload button or onchange the browse file input so you should do (call ajaxUpload(iframeObj) when you want to submit the form)
    3. The'ajaxUpload()' function will set the target of form to the iframe and the will submit your form.
    4. we have added a listener for iframe's onload so when the form uploads and the results came from server the iframeReady function will called and then the content of iframe will be fetched (here is the url of uploaded image) 5.(attention the output that you send in PHP file should be covered by HTML and body tags cause we can get the iframe's body content)

    The whole idea is this and I have tested please let me know if still there is any problem.

    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 file (saveImage_ajax.php) (or anything you want.)

    <?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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器