XML/HTML代码
- <!--
- * @Description: npage.vue
- * @Version: 1.0
- * @Author: LiuXia
- * @Date: 2022-08-01 20:32:06
- * @LastEditors: Jesse Liu
- * @LastEditTime: 2023-07-17 20:38:42
- -->
- <template>
- <div class="wscn-http404-container">
- <h1 style="line-height:300px; text-align:center">npage.vue (新测试文件)</h1>
- <div>time:</div>
- </div>
- </template>
- <script>
- import { parseTime } from '@/utils'
- import { downloadFile } from "@/utils/getFile";
- import { fileLinkToStreamDownload , urlFile } from '@/utils/down'
- export default {
- name: 'PageTest',
- computed: {
- message() {
- return 'PageTest'
- },
- parseTime: parseTime
- },
- methods:{
- downfile(filePath){
- //https://bbwx.kaitaiming.com/image/group1/M00/24/AE/rBBlxWS0vaqAR8ltAAGsWlc-FnY677.pdf
- // 后端上传文件返回请求的filePath地址
- console.log( filePath, 3333333 );
- // 获取文件名
- let fileName = urlFile(filePath, 1);
- // 获取文件后缀
- let fileExtension = urlFile(filePath, 2);
- // url下载
- fileLinkToStreamDownload(filePath,fileName,fileExtension);
- }
- },
- mounted() {
- this.downfile('http://localhost:9527/image/group1/M00/24/AE/rBBlxWS0vaqAR8ltAAGsWlc-FnY677.pdf');
- this.$store.dispatch("case/casesList/downloadFile",{}).then((res)=>{
- let data = res.data;
- let headers = res.headers;
- /*** 调用下载文件 ***/
- //downloadFile(data, headers)
- })
- },
- }
- </script>
- <style lang="scss" scoped>
- </style>
JavaScript代码
- /*
- * @Description: down.js
- * @Author: Jesse Liu
- * @Date: 2023-02-06 16:27:18
- * @LastEditors: Jesse Liu
- * @LastEditTime: 2023-07-17 20:20:05
- */
- export function fileLinkToStreamDownload(url, fileName, type) {
- let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;
- if (!reg.test(url)) {
- throw new Error("传入参数不合法,不是标准的文件链接");
- } else {
- let xhr = new XMLHttpRequest();
- xhr.open('get', url, true);
- xhr.setRequestHeader('Content-Type', `application/${type}`);
- xhr.responseType = "blob";
- xhr.onload = function () {
- if (this.status == 200) {
- //接受二进制文件流
- console.log(this)
- var blob = this.response;
- const blobUrl = window.URL.createObjectURL(blob);
- // 这里的文件名根据实际情况从响应头或者url里获取
- const a = document.createElement('a');
- a.href = blobUrl;
- a.download = fileName;
- a.click();
- window.URL.revokeObjectURL(blobUrl);
- }
- }
- xhr.send();
- }
- }
- // 获取url中需要的数据 type 1: 获取文件名 2:获取后缀 3:获取文件名+后缀 4:获取文件前缀
- export function urlFile(url, type) {
- let filename = url.substring(url.lastIndexOf('/') + 1)
- switch (type){
- case 1: return filename; break;
- case 2: return filename.substring(filename.lastIndexOf(".") + 1); break;
- case 3: return filename.substring(0, filename.lastIndexOf(".")); break;
- case 4: return url.substring(0, url.lastIndexOf('/') + 1)
- }
- }