关于#jquery#的问题:Jquery+ajax post请求如何下载文件流(语言-javascript)

Jquery+ajax post请求如何下载文件流,

const xhr = new XMLHttpRequest();
                xhr.open('POST', 'http://192.168.3.100:8999/sheng/importTemplate', true);
                //定义responseType='blob', 是读取文件成功的关键,这样设置可以解决下载文件乱码的问题
                xhr.responseType = "blob";    
                xhr.onload = () => {
                //'\ufeff' 这个变量是定义字符集为utf-8, 防止中文乱码的问题。
                // {type: 'application/msword'} 根据文档类型来定义这个type。MIMA type
                  const blob = new Blob(["\ufeff", xhr.response], {type: 'application/msword'});
                  const blobUrl = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.style.display = 'none';
                  a.href = blobUrl;
                  a.target = '_blank';
                  a.click();
                  }              
                             
                xhr.send(null);

上面这种调用直接报错URL.createObjectURL is not a function

img

加个window试下:


  const xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://192.168.3.100:8999/sheng/importTemplate', true);
  //定义responseType='blob', 是读取文件成功的关键,这样设置可以解决下载文件乱码的问题
  xhr.responseType = "blob";    
  xhr.onload = () => {
    //'\ufeff' 这个变量是定义字符集为utf-8, 防止中文乱码的问题。
    // {type: 'application/msword'} 根据文档类型来定义这个type。MIMA type
    const blob = new Blob(["\ufeff", xhr.response], {type: 'application/msword'});
    const blobUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = blobUrl;
    a.target = '_blank';
    a.click();
  }              
                             
 xhr.send(null);
 

jQuery AJAX 使用 XMLHttpRequest 对象来下载文件流,以便在不重新加载整个页面的情况下获取文件内容。可以使用 jQuery 的 $.ajax() 方法来实现,具体步骤如下:1. 创建一个XMLHttpRequest对象(xhr)。
2. 使用xhr.open()方法打开一个连接,可以发送请求给服务器。
3. 使用xhr.responseType = "blob"来设置响应类型为文件流。
4. 使用xhr.onload()方法处理响应。
5. 使用URL.createObjectURL()方法创建一个文件URL。
6. 使用a标签的href属性下载文件。


downloadFile = ((fileurl, filename) => { //fileurl文件地址(一般是接口返回) filename文件下载后的名字
        console.log("3333")
        var a = document.createElement('a');
        a.download = filename; //下载后文件名
        a.style.display = 'none';
        var blob = new Blob([fileurl]);  // 字符内容转变成blob地址 二进制地址
        a.href = URL.createObjectURL(blob);
        document.body.appendChild(a);
        a.click();                        // 触发点击
        document.body.removeChild(a);    // 然后移除
 
    });