如何知道向iframe提交表单和文件是否失败


How to know if submission of form, with files, to iframe fails

我使用iframe构建了一个照片提交。问题是如何知道文件是否由于新网络延迟或断开连接而无法提交。这样的事情有活动吗?或者,如果时间太长,如果有办法取消,我就取消它。我知道什么时候完成,因为来自服务器的回复是一个javascript函数,它被加载为recevied,但如果我没有收到任何东西该怎么办!

<form action="iframe.php" target="my-iframe" method="post">
    <label for="text">Some text:</label>
    <input type="file" name="file" id="file">
    <input type="submit" value="post">
</form>
<iframe name="my-iframe" src="iframe.php"></iframe>

 <script>
     function img_upload_done(opn,img,photo_number){ // opn holds boolen if img uploaded succefully
           //do something
     }
 </script>

        <?php
        //getting the directory of the this file
           $destination_path = getcwd().DIRECTORY_SEPARATOR;
            $name = rand (100,1000);
           $result = 0;
           $filename=$_FILES['file']['name'];
           $ext = pathinfo($filename, PATHINFO_EXTENSION) ; 
         // setting up the directory of the file uploaded
           $target_path = $destination_path . $name .".". $ext;
         //making sure the file has been uploaded in the specified directory
           if(@move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
              $result = 1;
           }
           sleep(0);
        ?>
        <script language="javascript" type="text/javascript">
           window.top.window.img_upload_done(<?php echo $result.",'"".$name .".". $ext."'",".$_POST["photo-number"]; ?>);
        </script>



         <?php
         //This function separates the extension from the rest of the file name and returns it
         function findexts ($filename) {
            $filename = strtolower($filename) ;
             $exts = split("[/''.]", $filename) ;
             $n = count($exts)-1;
             $exts = $exts[$n];
             return $exts;
         }
         //This applies the function to our file
         ?>

您可以使用window.postMessage()函数向页面发送失败或成功消息。

在你的主页上,它可能看起来像这样:

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
  var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
  if (origin !== "http://www.your-url.com")
    return;
  // ...
}

在iFrame中,在文件保存(或失败)后,您可以执行以下操作:

// where to send messages with postMessage
var target_origin = 'http://www.your-url.com';
parent.postMessage( {'success': 'true'}, target_origin );

更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage