file.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * 统一文件预览处理
  3. * @param url 文件链接
  4. * @param name 文件名(可选,用于提示)
  5. */
  6. export const previewFile = (url: string, name?: string) => {
  7. if (!url) {
  8. return uni.showToast({ title: '文件链接不存在', icon: 'none' });
  9. }
  10. // #ifdef H5
  11. window.open(url);
  12. // #endif
  13. // #ifndef H5
  14. uni.showLoading({ title: name ? `正在打开 ${name}...` : '正在打开文件...' });
  15. uni.downloadFile({
  16. url,
  17. success: (res) => {
  18. if (res.statusCode === 200) {
  19. uni.openDocument({
  20. filePath: res.tempFilePath,
  21. showMenu: true,
  22. success: () => uni.hideLoading(),
  23. fail: () => {
  24. uni.hideLoading();
  25. uni.showToast({ title: '当前平台暂不支持打开该类型文件', icon: 'none' });
  26. }
  27. });
  28. } else {
  29. uni.hideLoading();
  30. uni.showToast({ title: '下载失败', icon: 'none' });
  31. }
  32. },
  33. fail: () => {
  34. uni.hideLoading();
  35. uni.showToast({ title: '网络异常,下载失败', icon: 'none' });
  36. }
  37. });
  38. // #endif
  39. };