jquery.blob.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. (function($) {
  2. /**
  3. * 让 jQuery 支持 Blob 类型
  4. */
  5. $.ajaxTransport('+*', function(options, originalOptions, jqXHR) {
  6. if (window.FormData && ((options.dataType &&
  7. (options.dataType === 'blob' || options.dataType === 'arraybuffer')) ||
  8. (options.data && ((window.Blob && options.data instanceof Blob) ||
  9. (window.ArrayBuffer && options.data instanceof ArrayBuffer)))
  10. )) {
  11. return {
  12. /**
  13. * Return a transport capable of sending and/or receiving blobs - in this case, we instantiate
  14. * a new XMLHttpRequest and use it to actually perform the request, and funnel the result back
  15. * into the jquery complete callback (such as the success function, done blocks, etc.)
  16. *
  17. * @param headers
  18. * @param completeCallback
  19. */
  20. send: function(headers, completeCallback) {
  21. var xhr = new XMLHttpRequest(),
  22. url = options.url || window.location.href,
  23. type = options.type || 'GET',
  24. dataType = options.dataType || 'text',
  25. data = options.data || null,
  26. async = options.async || true,
  27. key;
  28. xhr.addEventListener('load', function() {
  29. var response = {},
  30. status, isSuccess;
  31. isSuccess = xhr.status >= 200 && xhr.status < 300 || xhr.status === 304;
  32. if (isSuccess) {
  33. response[dataType] = xhr.response;
  34. } else {
  35. // In case an error occured we assume that the response body contains
  36. // text data - so let's convert the binary data to a string which we can
  37. // pass to the complete callback.
  38. response.text = String.fromCharCode.apply(null, new Uint8Array(xhr.response));
  39. }
  40. completeCallback(xhr.status, xhr.statusText, response, xhr.getAllResponseHeaders());
  41. });
  42. xhr.open(type, url, async);
  43. xhr.responseType = dataType;
  44. for (key in headers) {
  45. if (headers.hasOwnProperty(key)) xhr.setRequestHeader(key, headers[key]);
  46. }
  47. xhr.send(data);
  48. },
  49. abort: function() {
  50. jqXHR.abort();
  51. }
  52. };
  53. }
  54. });
  55. })(window.jQuery);