Vue中是用downloadjs实现文件下载

2,613 阅读1分钟

本文在胖蔡叨叨叨首发,点击查看原文.


1ed72c09f5e3fb0

Vue中使用downlaodjs库实现浏览器中文件的下载,可以防止通过a标签下载导致txt,jpg等直接展示不下载的问题。

1、downloadjs下载

$ npm i downloadjs -S

 

2、 Vue中使用

创建一个vue 页面组件。

 

<template>
  <div style="margin:20px">
     <button @click="downloadText">点击下载</button>
  </div>
</template>

<script>
import download from "downloadjs";
export default {
  methods: {
    download() {
       download(this.url);
    },
  },
data() {
  return {
      url:'/test.txt',
  };
 },
};
</script>

 

3、常用api

  • 纯文本下载成文件

download("hello world", "dlText.txt", "text/plain");

  • 通过文件的dataURL下载
download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");
  • 通过blob下载
download(new Blob(["hello world"]), "dlTextBlob.txt", "text/plain");
  • 通过文件的地址
download("/robots.txt");
  • 文本 UInt8 数组
var str= "hello world",	arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
  arr[b]=a.charCodeAt();
});

download( arr, "textUInt8Array.txt", "text/plain" );