Ajax文件上传(使用Iframe)返回并使用文件名进行其他操作

简而言之,我想从iFrame中获取刚刚上传的文件的文件名。

首先让我告诉你,我确实有一个或多或少的工作ajax上传脚本(即现在适合我的需要)。 这很简单,如下:

我可以通过按下show-upload-form按钮来“包含”此表单,以便可以动态地将此表单添加到页面中。 现在,当点击提交按钮时,“upload.php”将处理上传并将文件名放在iFrame中。 由于我是iFrame的所有者,我尝试在upload.php中使用带有ID的echo(其中$ title是给定文件的’clean’版本)。

 echo ' . $title . '' 

(所以我上传后我的iframe看起来像:

  somefile.png  

所以我可以使用以下提交function获取file_path:

 $('#submit').live('click', function() { upload_form.find('form').attr('action', UPLOAD_SCRIPT_URL).submit(); var path = upload_form.find('iframe').contents().find('#file_path').attr('path'); /* I would like to do more actions with the path here */ return false; // So it can be used with multiple forms on the screen }); 

所以上传工作,但pathundefined ,这是非常明显的,因为文件submit()和上传不是即时的。 现在我考虑添加一个小延迟,但我也无法让它工作。

所以,我希望有一些.submit(function(){ }); 回调函数(这不是这个版本的submit(function(){}) ,但也许有一些函数或function.submit()我不知道)。

那么如何在上传文件后从iFrame获取#file_path path attribute (即上传的文件路径)。

use: var path = $('#upload_form').find('iframe').contents().find('#file_path').val();

输入“mutliple”,类似的东西:

 var $fileInput = $('#upload_form').find('iframe').contents().find('#file_path'); var fileInput = $fileInput[0]; if ( $this.prop('multiple') ) { for ( var i=0; i 

请注意,您应该在输入中输入id“file_path”( )或将选择器更改为$('#upload_form').find('iframe').contents().find('input:file');

编辑 :我想我更了解你想做什么:

 $('#submit').live('click', function() { $form = $(this).closest('form') $.post($form.attr('target'), $.serialize($form), function(data) { var path = upload_form.find('iframe').contents().find('#file_path').attr('path'); // do something (data is the response from 'upload_form' file }); return false; // So it can be used with multiple forms on the screen }); 

$ .post函数替换标准的提交函数。 (实际上你可以在表格中使用它)。 我可以替换0

使用setTimeout调用附加函数并检查是否可以获取图像,否则再次重用setTimeout。 然后上传图像并可用于其他操作:

 $('#upload_submit').live('click', function() { upload_form.find('form').attr('action', UPLOAD_SCRIPT_URL).submit(); setTimeout("include_image()", 2000); $('#editor').focus(); return false; // so you don't interrupt forms }); 

现在在include_image中,您可以尝试请求图像,如果有效则执行其他操作

 function include_image() { var file_path = upload_form.find('iframe').contents().find('#file_path').attr('path'); if (typeof file_path !== 'undefined') document.execCommand('InsertImage', false, file_path); else setTimeout("include_image()", 1000); } 

也许如果文件总是非常小,延迟时间可能会更低