0
Follow
0
View

Questions about #jquery# : How to download file streams for Jquery+ajax post requests(language-javascript)

cynthia_5199 注册会员
2023-02-27 23:22

jQuery AJAX uses the XMLHttpRequest object to download the file stream so that it can get the file contents without reloading the entire page. You can do this using the $.ajax() method of jQuery, as follows: 1. Create an XMLHttpRequest object(xhr).
2. open a connection using the xhr.open() method to send requests to the server.
3. Use xhr.responseType = "blob" to set the response type to file stream.
4. Process the response using the xhr.onload() method.
5. Create a file URL using the url.createObjecturl() method.
6. Download the file using the href attribute of the a tag.

patvice 注册会员
2023-02-27 23:22
) var a = document.create Element(' a ') ; a.download = filename; //下载后文件名 a.style.display = 'none'; var blob = new Blob([ fileurl ]) ; // 字符内容转变成blob地址 二进制地址 a.href = URL . create ObjectURL( blob ) ; document.body.append Child( a ) ; a.click () ; // 触发点击 document.body.remove Child( a ) ; // 然后移除 }); .
< !- - - - - >
yangyue12306 注册会员
2023-02-27 23:22

Add a 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);
 

About the Author

Question Info

Publish Time
2023-02-27 23:22
Update Time
2023-02-27 23:22