通过HTTP请求获取数据(resData),然后使用浏览器的下载功能将数据保存到本地文件
需要下载一个文件到本地保存的时候,前端需要做以下:
this.$http.getApi(postData).then(resData => {
let url = window.URL.createObjectURL(resData);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
let storage = window.localStorage;
let newFileName = storage.getItem("nowExportFileName");
console.log(newFileName);
link.setAttribute(
"download",
newFileName && newFileName != "undefined" ? newFileName : fileName
);
document.body.appendChild(link);
link.click();
});
-
this.$http.getApi(postData).then(resData => { ... });:发起一个HTTP GET请求,使用this.$http.getApi方法,postData是请求的数据。当请求成功后,执行回调函数,将返回的数据保存在resData中。 -
let url = window.URL.createObjectURL(resData);:使用window.URL.createObjectURL方法创建一个 Blob URL,该 URL 可以代表二进制数据(例如文件内容)。 -
let link = document.createElement("a");:创建一个a元素,用于模拟点击下载链接。 -
link.style.display = "none";:将link元素设置为不可见,以确保用户不会看到这个元素。 -
link.href = url;:将链接的href属性设置为之前创建的 Blob URL,这样点击链接时将会下载对应的数据。 -
let storage = window.localStorage;:获取本地存储对象。 -
let newFileName = storage.getItem("nowExportFileName");:从本地存储中获取名为 "nowExportFileName" 的项,这可能是一个用于指定下载文件名的值。 -
console.log(newFileName);:在控制台输出newFileName,用于调试和验证。 -
link.setAttribute("download", newFileName && newFileName != "undefined" ? newFileName : fileName);:设置link元素的download属性,该属性指定下载文件时的文件名。如果存在newFileName且不是 "undefined",则使用newFileName,否则使用默认的fileName。 -
document.body.appendChild(link);:将link元素添加到文档的body中。 -
link.click();:模拟点击链接,触发文件下载。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!