How to get blob data using javascript XmlHttpRequest by sync
2014-11-11 20:26
1076 查看
Tested:
Firefox 33+ OK
Chrome 38+ OK
IE 6 -- IE 10 Failed
Thanks to 阮一峰's blog: http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html
The sample shows how to get blob data using javascript XmlHttpRequest by sync.
The w3c tell us cannot set responseType when async is false.
FROM: http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/ If async is false, the JavaScript global environment is a document environment, and either the anonymous flag is set, the timeout attribute value is not zero, the withCredentials attribute value is true, or the responseType attribute value is not the empty string, throw an "InvalidAccessError" exception and terminate these steps.
The result is that the type of XMLHttpRequest.response always string, you must change string to blob.
if you not set "charset=x-user-defined", the string is ascii by default. The XMLHttpRequest.response is not correct, some bytes are changed.
I set to utf-8 or utf-16 also for test, but failed.
when using utf-8, the length of XMLHttpRequest.response is not correct
when using utf-16, the length equals to Real-Length/2. the problem is when Real-Length is odd I cannot get the last byte.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="aabb"></div>
<script>
var URL = URL || window;
function saveAs(blob, filename) {
var type = blob.type;
var force_saveable_type = 'application/octet-stream';
if (type && type != force_saveable_type) {
var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
}
var url = URL.createObjectURL(blob);
console.log(url);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = url;
save_link.download = filename;
save_link.text = 'ffff';
/*
// in firefox 33+
var m = document.getElementById('aabb');
m.innerHTML = '<a href="' +url+ '">FFF</a>';
*/
// in chrome 38+
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
URL.revokeObjectURL(url);
}
function binaryToBlob(data) {
var l = data.length, arr = new Uint8Array(l);
for(var i = 0; i < l; i++) {
arr[i] = data.charCodeAt(i);
}
return new Blob([arr], { type: 'image/octet-stream'})
};
(function(){
var r = new XMLHttpRequest();
r.open("GET", 'a.tif', false);
r.overrideMimeType('text/plain; charset=x-user-defined'); // this line is very important ,the charset must be x-user-defined
r.send();
var blob = binaryToBlob(r.response);
blob.fileType = "image/octet-stream";
saveAs(blob, 'res.tif');
})();
</script></body></html>
Firefox 33+ OK
Chrome 38+ OK
IE 6 -- IE 10 Failed
Thanks to 阮一峰's blog: http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html
The sample shows how to get blob data using javascript XmlHttpRequest by sync.
The w3c tell us cannot set responseType when async is false.
FROM: http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/ If async is false, the JavaScript global environment is a document environment, and either the anonymous flag is set, the timeout attribute value is not zero, the withCredentials attribute value is true, or the responseType attribute value is not the empty string, throw an "InvalidAccessError" exception and terminate these steps.
The result is that the type of XMLHttpRequest.response always string, you must change string to blob.
if you not set "charset=x-user-defined", the string is ascii by default. The XMLHttpRequest.response is not correct, some bytes are changed.
I set to utf-8 or utf-16 also for test, but failed.
when using utf-8, the length of XMLHttpRequest.response is not correct
when using utf-16, the length equals to Real-Length/2. the problem is when Real-Length is odd I cannot get the last byte.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="aabb"></div>
<script>
var URL = URL || window;
function saveAs(blob, filename) {
var type = blob.type;
var force_saveable_type = 'application/octet-stream';
if (type && type != force_saveable_type) {
var slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
}
var url = URL.createObjectURL(blob);
console.log(url);
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = url;
save_link.download = filename;
save_link.text = 'ffff';
/*
// in firefox 33+
var m = document.getElementById('aabb');
m.innerHTML = '<a href="' +url+ '">FFF</a>';
*/
// in chrome 38+
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
URL.revokeObjectURL(url);
}
function binaryToBlob(data) {
var l = data.length, arr = new Uint8Array(l);
for(var i = 0; i < l; i++) {
arr[i] = data.charCodeAt(i);
}
return new Blob([arr], { type: 'image/octet-stream'})
};
(function(){
var r = new XMLHttpRequest();
r.open("GET", 'a.tif', false);
r.overrideMimeType('text/plain; charset=x-user-defined'); // this line is very important ,the charset must be x-user-defined
r.send();
var blob = binaryToBlob(r.response);
blob.fileType = "image/octet-stream";
saveAs(blob, 'res.tif');
})();
</script></body></html>
相关文章推荐
- How To Do A JavaScript Cross-Domain POST or GET With jQuery or XMLHttpRequest
- How To Submit Form Data by Using XMLHTTP or ServerXMLHTTP Object
- How To Read and Write BLOB Data by Using ADO.NET with Visual C# .NET
- How to get pure json data by ajax request
- How To Transfer XML Data to Microsoft Excel 2002 by Using Visual C# .NET
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
- How To Read and Write BLOB Data by Using ADO.NET with Visual C# .NET
- How to use insert or retrieve data by using Core Data in iOS
- How To Create an ASP.NET HTTP Handler by Using Visual C# .NET
- Get MSN ADS by xmlHttpRequest
- How To Generate An XML File As A Target Datastore Using ODI In An Integration Interface ? [ID 454268
- How to find a node by its text using the GetNodeByText method
- SQL: How to get a series of dates in sql using connect by
- how to get Multilevel BOM in Windchill by using...
- How to use HttpWebRequest to post data to another page which is on another server
- To get QueryString by using javascript
- How to populate the datagrid on background thread with data binding by using Visual C#