How Do I Download A File From External Url To Variable?
Solution 1:
What your asking to do is pretty straight forward with in modern browsers with an XMLHTTPRequest. For example:
functionload(url, callback) {
var xhr = newXMLHTTPRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
};
xhr.open("GET", url, true);
}
load("site.com/t.txt", function (contents) {
// contents is now set to the contents of "site.com/t.txt"
});
But to ensure complete browser compatibility with Internet Explorer a little more code is required since Internet Explorer uses the ActiveXObject instead of XMLHTTPRequest.
functioncreateXHR() {
if (typeofXMLHTTPRequest === "undefined") {
if (createXHR._version) returnnewActiveXobject(createXHR._version);
else {
var versions = [
"Micrsoft.XMLHTTP",
"Msxml2.XMLHTTP",
"Msxml2.XMLHTTP",
"Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP.4.0",
"Msxml2.XMLHTTP.5.0",
"Msxml2.XMLHTTP.6.0"
];
var i = versions.length;
while (--i) try {
var v = versions[i], xhr = newActiveXObject(v);
createXHR._version = v;
return xhr;
} catch {}
}
} elsereturnnewXMLHTTPRequest();
}
functionload(url, callback) {
var xhr = createXHR();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
};
xhr.open("GET", url, true);
}
I would really recommend using a library such as jQuery instead of this. For more information
Solution 2:
As long as you are not working against the Same Origin Policy, this is quite easy. In this case, the domains match if your script is embedded in a page from foo.com and requesting a file foo.com/* and not subdomain.foo.com/*.
You just need to make a GET request with XMLHttpRequest
for the file and read the file's contents from the response.
If the file is on foo.com but the page isn't, you'll need to host the script on foo.com and then include it in this page with <script src="foo.com/filerequestscript.js"></script>
. (Of course, if you don't control foo.com, that's not likely to happen.)
Post a Comment for "How Do I Download A File From External Url To Variable?"