ali_oss.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const AliOss = (function (){
  2. const setting = {
  3. hint: true
  4. };
  5. const downloadFile = function (url, filename) {
  6. axios.get(url, {responseType: 'blob' }).then(res => {
  7. saveAs(res.data, filename);
  8. });
  9. };
  10. const downloadFileSync = function(url) {
  11. return new Promise((resolve, reject) => {
  12. axios.get(url, {responseType: 'blob'}).then(res => {
  13. resolve(res.data);
  14. }).catch(err => {
  15. reject(err);
  16. });
  17. })
  18. };
  19. const zipFiles = function (files, filename = '打包.zip', successCallback, errorCallback) {
  20. const zip = new JSZip();
  21. const download = [], fails = [];
  22. files.forEach(f => {
  23. download.push(downloadFileSync(f.filepath).then(data => {
  24. if (setting.hint) {
  25. toastr.success(`文件 “${f.filename + f.fileext}” 下载成功...`);
  26. }
  27. zip.file(f.filename + f.fileext, data, {binary: true});
  28. }).catch(err => {
  29. fails.push(f);
  30. }));
  31. });
  32. Promise.all(download).then(() => {
  33. toastr.clear();
  34. if (fails.length < files.length) {
  35. if (setting.hint) {
  36. toastr.success('所有文件下载成功,压缩中...');
  37. }
  38. zip.generateAsync({ type: "blob" }).then(content => {
  39. saveAs(content, filename);
  40. successCallback && successCallback(fails);
  41. });
  42. } else {
  43. errorCallback && errorCallback(fails);
  44. }
  45. })
  46. };
  47. const setSetting = function(data) {
  48. if (!data) return;
  49. setting.hint = data.hint || setting.hint;
  50. };
  51. return { downloadFile, downloadFileSync, zipFiles, setSetting }
  52. })();