ajax.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. function getError(action, option, xhr) {
  2. let msg;
  3. if (xhr.response) {
  4. msg = `${xhr.response.error || xhr.response}`;
  5. } else if (xhr.responseText) {
  6. msg = `${xhr.responseText}`;
  7. } else {
  8. msg = `fail to post ${action} ${xhr.status}`;
  9. }
  10. const err = new Error(msg);
  11. err.status = xhr.status;
  12. err.method = 'post';
  13. err.url = action;
  14. return err;
  15. }
  16. function getBody(xhr) {
  17. const text = xhr.responseText || xhr.response;
  18. if (!text) {
  19. return text;
  20. }
  21. try {
  22. return JSON.parse(text);
  23. } catch (e) {
  24. return text;
  25. }
  26. }
  27. export default function upload(option) {
  28. if (typeof XMLHttpRequest === 'undefined') {
  29. return;
  30. }
  31. const xhr = new XMLHttpRequest();
  32. const action = option.action;
  33. if (xhr.upload) {
  34. xhr.upload.onprogress = function progress(e) {
  35. if (e.total > 0) {
  36. e.percent = e.loaded / e.total * 100;
  37. }
  38. option.onProgress(e);
  39. };
  40. }
  41. const formData = new FormData();
  42. if (option.data) {
  43. Object.keys(option.data).forEach(key => {
  44. formData.append(key, option.data[key]);
  45. });
  46. }
  47. formData.append(option.filename, option.file, option.file.name);
  48. xhr.onerror = function error(e) {
  49. option.onError(e);
  50. };
  51. xhr.onload = function onload() {
  52. if (xhr.status < 200 || xhr.status >= 300) {
  53. return option.onError(getError(action, option, xhr));
  54. }
  55. option.onSuccess(getBody(xhr));
  56. };
  57. xhr.open('post', action, true);
  58. if (option.withCredentials && 'withCredentials' in xhr) {
  59. xhr.withCredentials = true;
  60. }
  61. const headers = option.headers || {};
  62. for (let item in headers) {
  63. if (headers.hasOwnProperty(item) && headers[item] !== null) {
  64. xhr.setRequestHeader(item, headers[item]);
  65. }
  66. }
  67. xhr.send(formData);
  68. return xhr;
  69. }