hookehuyr

上传文件组件-实现pc端直接下载弹框

1 <!-- 1 <!--
2 * @Date: 2022-08-31 16:16:49 2 * @Date: 2022-08-31 16:16:49
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2024-07-27 13:07:02 4 + * @LastEditTime: 2024-07-27 19:30:34
5 * @FilePath: /data-table/src/components/FileUploaderField/index.vue 5 * @FilePath: /data-table/src/components/FileUploaderField/index.vue
6 * @Description: 文件上传控件 6 * @Description: 文件上传控件
7 --> 7 -->
...@@ -121,10 +121,62 @@ const downloadFile = (item) => { ...@@ -121,10 +121,62 @@ const downloadFile = (item) => {
121 window.location.href = item.url; 121 window.location.href = item.url;
122 } else { 122 } else {
123 // 不在微信内置浏览器中,直接打开下载链接 123 // 不在微信内置浏览器中,直接打开下载链接
124 - window.open(item.url, '_blank'); 124 + fileLinkToStreamDownload(item.url, item.name, item.name.split('.').pop());
125 } 125 }
126 } 126 }
127 127
128 +// TAG: 文件下载操作
129 +/**
130 + * 数据流下载
131 + * @param {*} url
132 + * @param {*} fileName
133 + * @param {*} type
134 + */
135 +const fileLinkToStreamDownload = (url, fileName, type) => {
136 + let reg =
137 + /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;
138 + if (!reg.test(url)) {
139 + throw new Error("传入参数不合法,不是标准的文件链接");
140 + } else {
141 + let xhr = new XMLHttpRequest();
142 + xhr.open("get", url, true);
143 + xhr.setRequestHeader("Content-Type", `application/${type}`);
144 + xhr.responseType = "blob";
145 + xhr.onload = function () {
146 + if (this.status == 200) {
147 + //接受二进制文件流
148 + var blob = this.response;
149 + downloadExportFile(blob, fileName, type);
150 + }
151 + };
152 + xhr.send();
153 + }
154 +}
155 +/**
156 + * 下载文件
157 + * @param {*} blob
158 + * @param {*} fileName
159 + * @param {*} fileType
160 + */
161 +const downloadExportFile = (blob, fileName, fileType) => {
162 + let downloadElement = document.createElement("a");
163 + let href = blob;
164 + if (typeof blob == "string") {
165 + downloadElement.target = "_blank";
166 + } else {
167 + href = window.URL.createObjectURL(blob); //创建下载的链接
168 + }
169 + downloadElement.href = href;
170 + downloadElement.download = fileName;
171 + document.body.appendChild(downloadElement);
172 + downloadElement.click(); //点击下载
173 + document.body.removeChild(downloadElement); //下载完成移除元素
174 + if (typeof blob != "string") {
175 + window.URL.revokeObjectURL(href); //释放掉blob对象
176 + }
177 +}
178 +/************ END ************/
179 +
128 // 文件类型中文页面显示 180 // 文件类型中文页面显示
129 const type_text = computed(() => { 181 const type_text = computed(() => {
130 return props.item.component_props.file_type; 182 return props.item.component_props.file_type;
......