纯前端实现:下载电子书 手机观看
个人需求:在pc下载电子书,在手机上看
几个关键步骤:
- vue-cli搭建项目,配置跨域,实现目标网址的文章截取
- 每篇文章,通过在浏览器中生成文件,无需接触任何服务器。这样我们会得到很多个文件,保存在自己的本地文件夹中。(注意把浏览器的”下载前询问每个文件的保存位置“选项置为否,不然每次都要询问。)
function download(filename, text) {var element = document.createElement('a');element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));element.setAttribute('download', filename);element.style.display = 'none';document.body.appendChild(element);element.click();document.body.removeChild(element);
}download("hello.txt","This is the content of my file :)");
- 把这个文件夹上传到微信的存储空间
- 新建微信小程序项目,读取微信云服务里的内容
wx.cloud.downloadFile({fileID:"test/第18章.html", // 文件 IDsuccess: (res) => {// 返回临时文件路径let tempFilePath = res.tempFilePath;let fs = wx.getFileSystemManager();let result = fs.readFileSync(tempFilePath, "utf-8");// 读取文件内容到resultthis.setData({html2: result,});},fail: console.error,});
- 发布微信小程序,这样就可以在手机上浏览电子书了。
纯前端实现:下载电子书 手机观看
个人需求:在pc下载电子书,在手机上看
几个关键步骤:
- vue-cli搭建项目,配置跨域,实现目标网址的文章截取
- 每篇文章,通过在浏览器中生成文件,无需接触任何服务器。这样我们会得到很多个文件,保存在自己的本地文件夹中。(注意把浏览器的”下载前询问每个文件的保存位置“选项置为否,不然每次都要询问。)
function download(filename, text) {var element = document.createElement('a');element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));element.setAttribute('download', filename);element.style.display = 'none';document.body.appendChild(element);element.click();document.body.removeChild(element);
}download("hello.txt","This is the content of my file :)");
- 把这个文件夹上传到微信的存储空间
- 新建微信小程序项目,读取微信云服务里的内容
wx.cloud.downloadFile({fileID:"test/第18章.html", // 文件 IDsuccess: (res) => {// 返回临时文件路径let tempFilePath = res.tempFilePath;let fs = wx.getFileSystemManager();let result = fs.readFileSync(tempFilePath, "utf-8");// 读取文件内容到resultthis.setData({html2: result,});},fail: console.error,});
- 发布微信小程序,这样就可以在手机上浏览电子书了。