Vue.js 具有原始右扩展名的Axios下载文件

Vue.js 具有原始右扩展名的Axios下载文件,vue.js,download,axios,blob,vuex,Vue.js,Download,Axios,Blob,Vuex,我有以下下载文件的vuex方法: downloadFile(context, url) { return new promise((resolve, reject) => { const method = "GET"; axios .request({ url: url, method, responseType: "b

我有以下下载文件的vuex方法:

   downloadFile(context, url) {
      return new promise((resolve, reject) => {
        const method = "GET";
        axios
          .request({
            url: url,
            method,
            responseType: "blob"
          })
          .then(response => {
            let fileURL = window.URL.createObjectURL(
              new Blob([response.data]),
              {
                type: response.headers["content-type"]
              }
            );
            let fileLink = document.createElement("a");
            fileLink.href = fileURL;
            let fileName = response.headers["content-disposition"].split(
              "filename="
            )[1];
         
            fileLink.setAttribute("download", fileName);
            document.body.appendChild(fileLink);

            fileLink.click();
            fileLink.remove();
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    }
我传递URL链接(从LaravelAPI获取)

大宗报价

文件总是以txt扩展名下载的问题

大宗报价

有什么方法可以获取文件扩展名?

如果端点不提供扩展名,可以将其添加到
文件名中。因此可能是:

-  fileLink.setAttribute("download", fileName);
+  const extention = 'pdf'; // example
+  fileLink.setAttribute("download", `${fileName}.${extention}`);

您的服务器没有在屏幕截图中发送文件扩展名。如果它不在
downloadFile
url
参数中,并且您无法修复服务器响应以包含它,那么您可以从
内容类型
推断它。您可以创建一个哈希,将每种内容类型链接到一个扩展

删除此项:

let fileName=response.headers[“内容处置”]。拆分(
“文件名=”
)[1];
将其替换为以下内容以捕获扩展:

const扩展={
'application/vnd.openxmlformats of icedocument.wordprocessingml.document':'docx',
'application/fake':'fake',//只是一个例子
//等。为每种内容类型添加另一行
}
const contentType=response.headers[“Content Type”];
const extension=extensions[contentType];
常量文件名='文件'.+扩展名;

这会将每个文件命名为“file”。

我有多种类型,我需要它是动态的@Adam OrlovIf backend不会给你关于文件类型的信息,你需要自己弄清楚使用什么扩展名。可能基于某些
标题
谢谢亲爱的,但我需要知道如何获得文件扩展当获取不同文件时,文件扩展名会发生更改?也许你可以根据这个标题来判断。你的服务器在屏幕截图中没有发送文件扩展名。因此,您可以1)修复服务器响应以包含扩展名,或2)从
内容类型推断扩展名,亲爱的@dani,是传递给
下载文件的
url
中的扩展名吗?如果是这样的话,你也可以从这里开始。不,它不包含扩展。有没有办法在常量变量中定义所有扩展类型@丹