downloader.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { isValidUrl, isOnlineUrl, isDataUrl } from './util';
  2. function transformBase64File(base64data) {
  3. return new Promise((resolve, reject) => {
  4. const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  5. if (!format) {
  6. console.error('base parse failed');
  7. reject();
  8. return;
  9. }
  10. const path = `${uni.env.USER_DATA_PATH}/temp_${Date.now()}.${format}`;
  11. const buffer = uni.base64ToArrayBuffer(bodyData.replace(/[\r\n]/g, ''));
  12. uni.getFileSystemManager().writeFile({
  13. filePath: path,
  14. data: buffer,
  15. encoding: 'binary',
  16. success() {
  17. resolve(path);
  18. },
  19. fail(err) {
  20. console.log(err);
  21. reject(err);
  22. }
  23. });
  24. });
  25. }
  26. function downloadFile(url) {
  27. return new Promise((resolve, reject) => {
  28. uni.downloadFile({
  29. url: url,
  30. success: function (res) {
  31. if (res.statusCode !== 200) {
  32. console.error(`downloadFile ${url} failed res.statusCode is not 200`);
  33. reject();
  34. return;
  35. }
  36. resolve(res.tempFilePath);
  37. },
  38. fail: function (error) {
  39. console.error(`downloadFile failed, ${JSON.stringify(error)} `);
  40. reject();
  41. }
  42. });
  43. });
  44. }
  45. /**
  46. * 下载文件
  47. * @param {String} url 文件的 url
  48. */
  49. export function download(url) {
  50. return new Promise((resolve, reject) => {
  51. if (!(url && isValidUrl(url))) {
  52. resolve(url);
  53. return;
  54. }
  55. if (isOnlineUrl(url)) {
  56. downloadFile(url).then(
  57. (path) => {
  58. resolve(path);
  59. },
  60. () => {
  61. reject();
  62. }
  63. );
  64. } else if (isDataUrl(url)) {
  65. transformBase64File(url).then(
  66. (path) => {
  67. resolve(path);
  68. },
  69. () => {
  70. reject();
  71. }
  72. );
  73. } else {
  74. resolve(url);
  75. }
  76. });
  77. }