js 实现文件下载/文件导出。

前端之家收集整理的这篇文章主要介绍了js 实现文件下载/文件导出。前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. POST方式进行文件导出;

  1. // url 下载URL
  2. fileName 下载文件名称
  3. function exportFile(url,fileName) {
  4. let xhr = new XMLHttpRequest();
  5. xhr.open("POST",url);
  6. xhr.responseType = "blob";
  7. xhr.onload = () => {
  8. let ctx = xhr.response;
  9. let blob = Blob([ctx]);
  10. if ("msSaveOrOpenBlob" in navigator) {兼容IE
  11. window.navigator.msSaveOrOpenBlob(blob,fileName);
  12. } else {
  13. let aLink = document.createElement("a");
  14. aLink.download = fileName;
  15. aLink.style.display = "none";
  16. aLink.href = URL.createObjectURL(blob);
  17. document.body.appendChild(aLink);
  18. aLink.click();
  19. document.body.removeChild(aLink);
  20. }
  21. };
  22. xhr.send();
  23. }

使用方法:exportFile(url,fileName);

 

使用Angular方式进行导出:

  1. class ExportEvent {
  2. constructor( private http:HttpClient ){}
  3. url 下载URL
  4. fileName 下载文件名称
  5. exportFile(url,fileName){
  6. this.http.request("POST",url,{},{responseType:"blob"}).pipe()
           .subscribe(
  7. (res)=>{
  8. let blob = Blob([res]);
  9. window.navigator.msSaveOrOpenBlob(blob,fileName);
  10. } {
  11. let aLink = document.createElement("a");
  12. aLink.download = fileName;
  13. aLink.style.display = "none";
  14. aLink.href = URL.createObjectURL(blob);
  15. document.body.appendChild(aLink);
  16. aLink.click();
  17. document.body.removeChild(aLink);
  18. }
  19. },(error)=>{
  20. let reader = FileReader();
  21. reader.onload = (e)=>{
  22. if(e && e["target"]){
  23. let errorMsg = JSON.parse(e["target"]["result"]);
  24. if(errorMsg && errorMsg["code"]){
  25. console.log("有报错,出错了。。。。。");
  26. }
  27. }
  28. }
  29. error.error的值是一个Blob对象
  30. reader.readAsText(error.error);
  31. }
           );
  32. }
  33. }

 

2. GET方式进行文件导出;

  1. url 下载路径
  2. window.location = url;

 

猜你在找的Angularjs相关文章