Explorar o código

公共下载PDF文件

Rockery %!s(int64=3) %!d(string=hai) anos
pai
achega
2334dd763d
Modificáronse 1 ficheiros con 66 adicións e 2 borrados
  1. 66 2
      src/utils/rockeryutil.js

+ 66 - 2
src/utils/rockeryutil.js

@@ -3,10 +3,13 @@
  * @Author: Rockery
  * @Date: 2021-04-26 15:53:59
  * @LastEditors: Rockery
- * @LastEditTime: 2021-12-09 10:42:00
+ * @LastEditTime: 2021-12-29 17:56:27
  * @FilePath: \party_construct_web\src\utils\rockeryutil.js
  * @Copyright: Copyright (c) 2016~2021 Rockery(1113269755@qq.com)
  */
+import request from '@/utils/request';
+import { parseTime } from "@/utils/ruoyi";
+import { Message } from 'element-ui';
 
 /**
  * @description: 开启遮护罩
@@ -45,8 +48,69 @@ export function handleCloseLoading(paramLoading) {
  * 图片加载失败事件
  * @param {Object} ele
  */
- export function imgViewerOnerror(ele) {
+export function imgViewerOnerror(ele) {
   const img = ele.srcElement;
   img.src = require('@/assets/images/empty_img.png');
   img.onerror = null;
 }
+
+/**
+ * 常规下载PDF文件
+ * @param {String} pdfFileUrl PDF文件地址 必传
+ * @param {String} pdfFileName PDF文件别名 非必传
+ */
+export function regularDownloadPdfFile(pdfFileUrl, pdfFileName) {
+  if (pdfFileUrl) {
+    request({
+      url: pdfFileUrl,
+      method: 'get',
+      responseType: 'blob'
+    }).then(res => {
+      // 文件流
+      const blob = new Blob([res], { type: 'application/pdf;charset=utf-8' });
+
+      // 文件名称
+      const filename = `${pdfFileName || 'PDF文件'}_${parseTime(new Date(), "{y}-{m}-{d}")}_${new Date().getTime()}.pdf`;
+
+      // 执行文件下载操作
+      if (typeof window.navigator.msSaveBlob !== "undefined") {
+        window.navigator.msSaveBlob(blob, filename);
+        Message({
+          message: "下载PDF文件成功!",
+          type: 'success',
+          showClose: true,
+          center: true
+        });
+      } else {
+        // 创建一个指向该参数对象的URL
+        const blobURL = window.URL.createObjectURL(blob);
+
+        // 创建隐藏<a>标签进行下载
+        const tempLink = document.createElement("a");
+        tempLink.style.display = "none";
+        tempLink.href = blobURL;
+        tempLink.setAttribute("download", filename);
+        if (typeof tempLink.download === "undefined") {
+          tempLink.setAttribute("target", "_blank");
+        }
+        document.body.appendChild(tempLink);
+        tempLink.click();
+        window.URL.revokeObjectURL(blobURL);
+        document.body.removeChild(tempLink);
+        Message({
+          message: "下载PDF文件成功!",
+          type: 'success',
+          showClose: true,
+          center: true
+        });
+      }
+    }).catch(() => {});
+  } else {
+    Message({
+      message: "PDF文件地址不能为空!",
+      type: 'error',
+      showClose: true,
+      center: true
+    });
+  }
+}