无法从我发布的iframe获取文件名

时间:2012-08-11 20:53:39

标签: javascript jquery

我正在尝试使用jQuery和PHP上传图像。我知道有很多插件解决方案,但我正在使用它。我可以毫无问题地将文件上传到服务器,但对于我的生活,我无法弄清楚如何获取文件名,以便我可以显示图像。有没有办法从我发布的iframe获取文件名?这是我正在使用的代码:

jquery的

$('#file').change(function()
{ 
    var iframe = $('<iframe name="postiframe" id="postiframe" style="display:none" />');
    $("body").append(iframe);
    var form = $('#form');
    form.attr("action", "../hub.php?handler=add_item");
    form.attr("method", "post");
    form.attr("enctype", "multipart/form-data");
    form.attr("encoding", "multipart/form-data");
    form.attr("target", "postiframe");
    form.attr("file", $('#file').val());
    form.submit();
    $("#postiframe").load(function()
    {
        iframeContents=$("#postiframe")[0].contentWindow.document.body.innerHTML;
        console.log('added : '+iframeContents);                     
    });    
});

上面的代码只输出“added:”部分。非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

上传完成后,您必须echo / print来自服务器的filenamepath(最好在发布时text/HTMLiframe)所以您可以使用Javascript获取它,如问题代码中所示。

iframeContents=$("#postiframe")[0].contentWindow.document.body.innerHTML;
console.log('added : '+iframeContents);

你也可以编写一个新的JS请求来通过Ajax将上传的图像提取到一个新的PHP(例如echo JSON),但是如果你只想获得该表格中的上传文件则不需要提交。

答案 1 :(得分:0)

您可以使用 window.name 技术将一些字符串数据从iframe传递到主窗口。 使用的简短例子:

I帧:

//doing your stuff, when finished store what you need in window.name property
window.name = '{"key1":"mydata1","key2":"mydata2"}'
window.location.href='about:blank';

主窗口:

$(iframe).bind('load',function(){
    //triggered every time iframe's location is changed
    var iframe_data = this.contentWindow.name;
    if(!iframe_data.length) {
      //it's a first time iframe loaded
      return;
     }
    else{
      //iframe location is changed, we're expecting to receive some data
      $(this).unbind('load');
      console.log($.parseJSON(iframe_data));
      //{"key1":"mydata1","key2":"mydata2"}
    }

})

即使iframe放在另一个来源(域),它也应该有用。 我没有专门测试这段代码,但它应该可以工作,我从我的一个项目中复制了它