javascript 是否可以执行异步跨域文件上传?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6718664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to perform an asynchronous cross-domain file-upload?
提问by ?ime Vidas
It is possible! Read below.
有可能的!参见下文。
First of all, let me use this diagram to explain how asynchronous file uploadscan be achieved:
首先,让我用这个图来解释如何实现异步文件上传:
Sorry. I've shut down one of my domains, and the image is gone now. It was a really nice image though. This was before I found out that Stack Overflow enables uploading images via Imgur.
对不起。我关闭了我的一个域,现在图像消失了。不过,这是一个非常好的图像。这是在我发现 Stack Overflow 允许通过 Imgur 上传图像之前。
As you can see, the trick is to let the HTTP-response load into a hidden IFRAME element instead of the page itself. (This is done by setting the target
property of the FORM element when submitting the FORM with JavaScript.)
如您所见,诀窍是让 HTTP 响应加载到隐藏的 IFRAME 元素而不是页面本身。(这是通过target
在使用 JavaScript 提交 FORM 时设置FORM 元素的属性来完成的。)
This works. However, the problem I'm facing is that the server-side script is on a different domain. The FORM-submit is a cross-domain HTTP-request. Now, the server-side script has CORS enabled which gives my web-page the rights to read the response-data of HTTP-requests made from my page to that script - but that works only if I receive the HTTP-response via Ajax, ergo, JavaScript.
这有效。但是,我面临的问题是服务器端脚本位于不同的域上。FORM-submit 是一个跨域的 HTTP 请求。现在,服务器端脚本启用了 CORS,这使我的网页有权读取从我的页面向该脚本发出的 HTTP 请求的响应数据 - 但只有当我通过 Ajax 接收 HTTP 响应时才有效,因此,JavaScript。
However, int this case, the response is directed towards the IFRAME element. And once the XML response lands into the IFRAME, its URL will be the remove script - e.g. http://remote-domain.com/script.pl
.
然而,在这种情况下,响应是针对 IFRAME 元素的。一旦 XML 响应进入 IFRAME,其 URL 将是删除脚本 - 例如http://remote-domain.com/script.pl
.
Unfortunately, CORS does not cover this case (at least I think) - I am not able to read the contents of the IFRAME since its URL doesn't match the URL of the page (different domain). I get this error:
不幸的是,CORS 不包括这种情况(至少我认为) - 我无法读取 IFRAME 的内容,因为它的 URL 与页面的 URL(不同域)不匹配。我收到此错误:
Unsafe JavaScript attempt to access frame with URL hxxp://remote-domain.com/script.pl from frame with URL hxxp://my-domain.com/outer.html. Domains, protocols and ports must match.
不安全的 JavaScript 尝试从 URL hxxp://my-domain.com/outer.html 的框架访问 URL hxxp://remote-domain.com/script.pl 的框架。域、协议和端口必须匹配。
And since the contents of the IFRAME is an XML document, there is no JavaScript code inside the IFRAME which could make use of postMessage
or something.
而且由于 IFRAME 的内容是一个 XML 文档,因此 IFRAME 中没有可以使用的 JavaScript 代码postMessage
或其他东西。
So my question is: How can I get the XML contents from the IFRAME?
所以我的问题是:如何从 IFRAME 获取 XML 内容?
As I said above, I am able to retrieve cross-domain HTTP-responses directly (CORS enabled), but it seems that I am not able to read cross-domain HTTP-responses once they load into an IFRAME.
正如我上面所说,我能够直接检索跨域 HTTP 响应(启用 CORS),但是一旦它们加载到 IFRAME 中,我似乎无法读取跨域 HTTP 响应。
And as if this question is not unsolvable enough, let me exclude these solutions:
好像这个问题还不够无解,让我排除这些解决方案:
easyXDM and similar techniques which require an end-point on the remote domain,
altering the XML response (to include a SCRIPT element),
server-side proxy - I understand that I could have a server-side script on my domain which could serve as a proxy.
easyXDM 和需要远程域上的端点的类似技术,
更改 XML 响应(以包含 SCRIPT 元素),
服务器端代理 - 我知道我的域上可以有一个服务器端脚本,它可以用作代理。
So, apart from those two solutions, can this be done?
那么,除了这两种解决方案,还能做到这一点吗?
It can be done!!
可以办到!!
It turns out that it is possible to forge a XHR-request (Ajax-request) which imitates a multipart/form-data
FORM submit (which is used in the image above to upload the file to the server).
事实证明,可以伪造一个模拟multipart/form-data
FORM 提交的 XHR 请求(Ajax 请求)(在上图中用于将文件上传到服务器)。
The trick is to use FormData
constructor - read this Mozilla Hacks articlefor more information.
诀窍是使用FormData
构造函数——阅读这篇 Mozilla Hacks 文章了解更多信息。
This is how you do it:
这是你如何做到的:
// STEP 1
// retrieve a reference to the file
// <input type="file"> elements have a "files" property
var file = input.files[0];
// STEP 2
// create a FormData instance, and append the file to it
var fd = new FormData();
fd.append('file', file);
// STEP 3
// send the FormData instance with the XHR object
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://remote-domain.com/script.pl', true);
xhr.onreadystatechange = responseHandler;
xhr.send(fd);
The above method executes an asynchronous file-uplaod, which is equivalent to the regular file-upload described in the image above and achieved by submitting this form:
上述方法执行一个异步文件上传,相当于上图描述的常规文件上传,通过提交这个表单来实现:
<form action="http://remote-domain.com/script.pl"
enctype="multipart/form-data" method="post">
<input type="file" name="file">
</form>
Like a Boss :)
像一个老板一样 :)
采纳答案by Eli Grey
Just send a cross-domain XHR request with the data from the form instead of submitting the form. CORS is only for the former.
只需使用表单中的数据发送跨域 XHR 请求,而不是提交表单。CORS 仅适用于前者。
If you must do it the other way, negotiate with the frame using postMessage.
如果您必须以其他方式执行此操作,请使用 postMessage 与框架协商。
And since the contents of the IFRAME is an XML document, there is no JavaScript code inside the IFRAME which could make use of postMessage or something.
由于 IFRAME 的内容是一个 XML 文档,因此 IFRAME 中没有可以使用 postMessage 或其他东西的 JavaScript 代码。
How does that stop you? Include a script element under the HTML or SVG namespace (<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" src="..."/>
) anywhere in the XML.
这如何阻止你?<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" src="..."/>
在 XML 的任何位置的 HTML 或 SVG 命名空间 ( )下包含脚本元素。
回答by Halcyon
I think it can't be done with the way you're describing. Normally if you have cross domain issues you can solve it by a JSONp approach but that only works for GET requests. With HTML5 you could potentially send binary with the GET request but that's just iffy.
我认为按照您描述的方式无法完成。通常,如果您有跨域问题,您可以通过 JSONp 方法解决它,但这仅适用于 GET 请求。使用 HTML5,您可能会使用 GET 请求发送二进制文件,但这只是不确定的。
A solution would be to make the remote webservice available locally by proxying the request on the local webserver. This will cause additional load for your local webserver so I can imagine that it is infeasible. If the files are small and infrequent though, this will do nicely.
Another solution would be to start polling the server after you've sent the file. You could send along a token and poll the status of the server using regular JSONp. This way you don't need to read from the iframe.
Put the whole page in an iframe that runs on the remote server. This might just move the problem, but if the XML output is the final step in some process it's quite feasible.
一种解决方案是通过代理本地 web 服务器上的请求,使远程 web 服务在本地可用。这将为您的本地网络服务器带来额外的负载,所以我可以想象这是不可行的。如果文件很小而且很少出现,这会很好。
另一种解决方案是在发送文件后开始轮询服务器。您可以发送令牌并使用常规 JSONp 轮询服务器的状态。这样你就不需要从 iframe 中读取。
将整个页面放在在远程服务器上运行的 iframe 中。这可能只是解决了问题,但如果 XML 输出是某个过程的最后一步,那是非常可行的。
I'm sure you have a good reasons for the processing server to be on a different domain, but if it weren't you wouldn't have all these problems. Perhaps it's worthwhile to reconsider?
我确信您有充分的理由将处理服务器置于不同的域中,但如果不是这样,您就不会遇到所有这些问题。也许值得重新考虑?
回答by Mic
If you can, return an HTML page instead of the XML.
In that page you can use in a SCRIPT
tag the command:parent.postMessage
如果可以,请返回 HTML 页面而不是 XML。
在该页面中,您可以在SCRIPT
标签中使用以下命令:parent.postMessage
If you have to support older browsers(< IE8 mainly), you can write and read window.name
for messages below 2Mb.
如果您必须支持旧浏览器(主要< IE8),您可以编写和阅读window.name
2Mb以下的消息。
Both techniques allows you to pass string data between frames of different domains.
这两种技术都允许您在不同域的帧之间传递字符串数据。
Another technique is to use a setInterval
that will call repeatedly the remote domain from the parent page using JSONPto know the status.
另一种技术是setInterval
使用JSONP从父页面重复调用远程域以了解状态。
In any case, you will need a cooperation from the remote domain to get the data.
在任何情况下,您都需要远程域的合作才能获取数据。
回答by Jiri Kriz
The following approach is working in my setup (Firefox 3.6):
以下方法适用于我的设置(Firefox 3.6):
<!-- hidden target frame -->
<iframe name="load_target" id="load_target" onload="process(this);" src="#" ...>
<!-- get data from iframe after load and process them -->
<script type="text/javascript">
function process(iframe) {
var data = iframe.contentWindow.document.body.innerHTML;
// got test data="<xml><a>b</a></xml>"
}
</script>
It is working in Chrome as well, but it is needed to exclude a first onload call after the loading of the parent page. This is easily accomplished by setting a "global" variable which is tested in process()
.
它也适用于 Chrome,但需要在加载父页面后排除第一个 onload 调用。这可以通过设置在process()
.
ADDITION
添加
The method works together with a form
该方法与表单一起使用
<form action="URL" method="post" enctype="multipart/form-data" target="load_target">
which is submitted to URL
. This URL
needs to reside on the same domain as the parent page page.html
. If data from a REMOTE_URL
are to be downloaded, then URL
would be a PHP proxy.php
on the own domain with the content
提交给URL
. 这URL
需要与父页面位于同一个域中page.html
。如果REMOTE_URL
要下载来自 a 的数据,那么URL
将是proxy.php
在自己的域上的带有内容的 PHP
<?php echo file_get_contents("REMOTE_URL"); ?>
This is a simple approach - however, it is probably excluded by the condition (2) of the question. I have added it here to make my answer complete.
这是一种简单的方法 - 但是,它可能被问题的条件 (2) 排除在外。我在这里添加了它以使我的答案完整。
Other approaches, considering iframes only, are discussed by Mahemoffand Georges Auberger.
Mahemoff和Georges Auberger讨论了其他方法,仅考虑 iframe 。