jquery.form和跨域请求的文件上传

时间:2013-01-05 18:42:39

标签: jquery iframe file-upload jquery-forms-plugin asyncfileupload

我尝试使用jquery表单插件创建跨域文件上载表单,但我在firebug控制台中不断收到以下错误:

Permission denied to access property 'document'

它发生在jquery.form插件的以下行

403: var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;

如果我使用safari,我会收到此错误:

Unsafe JavaScript attempt to access frame with URL http://s1.test-host/index.php/upload/start?is-async=1 from frame with URL http://test-host/index.php/main/. Domains, protocols and ports must match.

for的html如下所示:

  <form action="http://s1.test-host//index.php/upload/start" method="post" accept-charset="utf-8" id="upload-form" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="1204000"  />
      <label for="file-input">Input File</label>
      <input type="file" name="file" value="" id="file-input" alt="Input File"  />
      <input type="submit" name="upload" value="Convert" id="start-upload" />
  </form>

javascript看起来像这样:

$(this).ajaxForm ({
    beforeSubmit: onFileFormSubmit,     // pre-submit callback
    success:      onFileFormSubmitEnd,  // post-submit callback
    resetForm:    true,             // reset the form after successful submit
    dataType:     'json',           // force response type to JSON
    iframe:       true              // force the form to be submitted using an iframe
});

目标php页面包含:

    if ($_SERVER['HTTP_ORIGIN']) {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        header('Access-Control-Max-Age: 1000');
        header('Access-Control-Allow-Headers: Content-Type');
    }
   ... // Usual upload handling code

但似乎没有任何效果。我甚至试图改变数据类型&#39;到&#39; jsonp&#39;并且还改为从&#39; post&#39;得到&#39;但是这一切都无济于事,我仍然会遇到同样的错误。如果我查看服务器,文件确实上传了,但是javascript无法调用成功函数。

谷歌搜索后,我发现可能还有其他解决方案,例如“JQuery文件上传”等。或者&#39; plupload&#39;但我真的需要一些简单的东西,我不想使用HTML5功能。

2 个答案:

答案 0 :(得分:1)

文件上传插件使用iframe上传文件。由于您无法在没有正确的CORS标头的情况下发布跨域,并且您无法向iframe提供CORS标头,因此这是不可能的。最好的选项是将其发布到您的服务器,然后根据需要使用服务器端代码将其移动到跨域。

答案 1 :(得分:0)

我知道您不想要任何花哨的东西,但对于没有完全XHR支持的浏览器中的跨域,我建议使用 jQuery-File-Upload 插件。它使用iframe将文件上传到另一个域。它需要更多的工作:

  • 您需要将上传服务器响应更改为插件expects
  • 您需要在原始服务器的某处上传result.html才能获得回复

如果您不想要UI内容,可以使用插件的基本版本。