Obtenga la URL del pdf desde la interfaz y realice la función de descarga en primer plano
Idea: use la solicitud get para obtener un flujo binario, luego conviértalo en un Blob, luego cree un DOMString a través de window.URL.createObjectURL(), y asígnelo al href de la etiqueta a. La implementación específica es la siguiente: Paso 1: obtenga solicitudes de la ruta de pdf
,
porque The blob requiere una secuencia binaria
/*
url: "http://124.127.246.224:9000/images/2022/10/17/c24f8fd7d53.pdf"
options: {title:"",fileType:"application/pdf"}
ele: a标签
*/
let getFile = (url, options, ele) => {
axios.get(url,{
responseType: 'blob' }).then(res => download(res, options, ele))
}
Paso 2: Convierta los datos devueltos a Blob
let download = (res, options, ele) => {
let blob = new Blob([res.data], {
type: options.fileType ? options.fileType : "application/octet-binary" });
let href = window.URL.createObjectURL(blob);
downloadBlob(href, options, ele);
}
Paso 3: Ejecute la descarga
Pitfall aquí: si no agrega ele.click (), debe hacer clic nuevamente para descargar el archivo. Si agrega clic en autollamada, se descargará dos veces, así que use la bandera para grabar
let flag = 1;
let downloadBlob = (blobUrl, options, ele) => {
ele.href = blobUrl;
ele.download = options.title;
flag++;
if ((flag % 2) == 0) {
ele.click();
window.URL.revokeObjectURL(blobUrl);//释放
}
}
Paso 4: llame al archivo vue
<el-button type="primary" @click="download(ele, index)">下载
<a :id="'d' + index"></a>
</el-button>
import {
getFile} from "@/utils/download"
download(data, index) {
let arr = data.url.split(".");
let options = {
title: data.title,
fileType: "application/"+arr[arr.length-1]
};
let link = document.getElementById("d" + index);
getFile(data.url,options,link)
},
El contenido completo del archivo js es el siguiente:
//download.js
import axios from "axios" //需要单独引入,因为当前.js文件不会被vue管理
axios.defaults.headers['Cache-Control'] = 'no-cache'
/*
url: "http://124.127.246.224:9000/images/2022/10/17/c24f8fd7d53.pdf"
options: {title:"",fileType:"application/pdf"}
ele: a标签
*/
let getFile = (url, options, ele) => {
axios.get(url, {
responseType: 'blob' }).then(res => download(res, options, ele))
}
let download = (res, options, ele) => {
let blob = new Blob([res.data], {
type: options.fileType ? options.fileType : "application/octet-binary" });
let href = window.URL.createObjectURL(blob);
downloadBlob(href, options, ele);
}
let flag = 1;
let downloadBlob = (blobUrl, options, ele) => {
ele.href = blobUrl;
ele.download = options.title;
flag++;
if ((flag % 2) == 0) {
ele.click();
window.URL.revokeObjectURL(blobUrl);
}
}
export {
getFile,
download,
downloadBlob
}
Si hay una mejor manera de escribir, las correcciones son muy bienvenidas, gracias ~