fileDownload.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import $config from "@/config/global.config.js"
  2. /***
  3. * 文件下载
  4. * @param {string} url 下载地址
  5. *
  6. * */
  7. export const fileDownload = (url) => {
  8. uni.showLoading({
  9. title: '加载中',
  10. mask: true
  11. });
  12. uni.downloadFile({
  13. url: `${$config.baseUrl}${url}`,
  14. timeout: 1000000,
  15. header: {
  16. 'apiToken': uni.getStorageSync('apiToken') //自定义请求头信息
  17. },
  18. success: (res) => {
  19. // console.log(res);
  20. uni.hideLoading();
  21. if (res.tempFilePath && res.statusCode === 200) {
  22. uni.openDocument({
  23. filePath: res.tempFilePath,
  24. success: () => {
  25. console.log('文档打开成功');
  26. uni.showToast({ title: '文件已打开,请点击右上角保存到手机', icon: 'none', duration: 3000 });
  27. },
  28. fail: (openErr) => {
  29. console.warn('openDocument 失败(可能不支持 .xlsx 预览)', openErr);
  30. }
  31. });
  32. } else {
  33. uni.showToast({ title: '文件下载失败', icon: 'none' });
  34. }
  35. },
  36. fail: (err) => {
  37. uni.hideLoading();
  38. console.error('请求失败', err);
  39. uni.showToast({ title: '请求失败', icon: 'none' });
  40. }
  41. });
  42. };
  43. /***
  44. * 打开文档预览
  45. * @param {string} url 文件网络地址
  46. *
  47. * */
  48. export const openDocument = (url) => {
  49. if (!url) return uni.showToast({ title: '文件地址不存在', icon: 'none' });
  50. uni.downloadFile({
  51. url: url,
  52. success: function (res) {
  53. let filePath = res.tempFilePath;
  54. uni.openDocument({
  55. filePath: filePath,
  56. // showMenu: true,
  57. success: function (res) {
  58. console.log('打开文档成功');
  59. uni.showToast({ title: '文件已打开,请点击右上角保存到手机', icon: 'none', duration: 3000 });
  60. }
  61. });
  62. }
  63. });
  64. };