前端常用的上传下载文件的几种方式,直接上传、下载文件,读取.xlsx文件数据,导出.xlsx数据

一、通过调用接口下载文件

const onExport = async () => {
  try {
    let res = await axios.request({
      method: 'POST',
      url: '请求地址',
      responseType: 'blob',
      params: { data: null },
      headers: { Authorization: 'Bearer ' + UserModule.token },//看看请求是否需要token
    });

    let reader = new FileReader();
    let data = res.data;
    reader.onload = (e: any) => {
      try {
        let fileName = window.decodeURI(
          decodeURIComponent(decodeURI(res.headers['content-disposition'].split(`''`)[1]))
        );
        let url = window.URL.createObjectURL(new Blob([data], { type: res.headers['content-type'] }));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (e: any) {
        message.error(e);
      }
    };
    reader.readAsText(data);
  } catch (err) {
    message.error('导出失败');
  }
};

二、将数组的对象数据导出到.xlsx文件中

  fnExport() {
    let data = [];
    let temp =    [
      {
        name:'小周',
        sex:'男',
        nation:'汉族'
      },
      {
        name:'小林',
        sex:'女',
        nation:'汉族'
      },
    ]
    temp.forEach((item: models.ExpertEditModel) => {
      data.push({
        姓名: item.name,
        性别: item.sex,
        民族: item.nation,
      });
    });
    const ws = XLSX.utils.json_to_sheet(data);
    // 新建book
    const wb = XLSX.utils.book_new();
    // 生成xlsx文件(book,sheet数据,sheet命名)
    XLSX.utils.book_append_sheet(wb, ws, '数据详情');
    // 写文件(book,xlsx文件名称)
    XLSX.writeFile(wb, '基本信息.xlsx');
  }

三、请求接口上传文件给后端

  async beforeAvatarUpload(file: any, fList: any) {
    if (!file) {
      this.$message.error('请先添加文件');
    } else {
      if (file) {
        try {
          const formData = new FormData();
          formData.append('file', file);
          //await api.Organizations.EduUploadSchool_PostAsync(formData);
          // 发起POST请求
			axios.request({
			  method: 'post',
			  url: 'your_backend_url',
			  data: formData,
			  headers: {
			    'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
			    // You might need other headers depending on your backend requirements
			  }
			})
          this.$message.success('上传成功');
        } catch (err) {
          this.$message.error('上传失败:' + err.message);
        }
      }
    }
  }

四、读取用户上传的.xlsx文件内容转成数组

html

        <el-upload
            action=""
            accept=".xlsx"
            :before-upload="getExcelFile"
        >
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        async getExcelFile(file) {
            if (!/\.(xlsx)$/.test(file.name.toLowerCase())) {
                console.log("请上传.xlsx格式的Excel文件");
            } else if (file) {
                try {
                    const res = await this.readExcel(file);//调用解析.xlsx文件方法
                } catch (error) {
                    console.log("上传错误:", error);
                }
            }
        },
        // 解析Excel
        readExcel(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();//创建FileReader对象,您可以将文件内容读取到内存中
                let getExcelList = [];// 用于存储从Excel中提取的数据
                reader.onload = (e) => {
                    try {
                        let data = e.target.result;
                        let workbook = XLSX.read(data, { type: "binary" });
                         // 遍历工作表
                        for (let item in workbook.SheetNames) {
                            let SheetName = workbook.SheetNames[item];
                            let sheetInfos = workbook.Sheets[SheetName];
                            // 将工作表内容转换为JSON格式
                            let excel = XLSX.utils.sheet_to_json(sheetInfos, { raw: true });
                            // 遍历每行数据并将特定字段添加到getExcelList数组中
                            excel.forEach((item) => {
                                getExcelList.push({
                                    name: item.姓名 ?? "",
                                    nation: item.民族 ?? "",
                                    school: item.学校 ?? "",
                                });
                            });
                        }
                        console.log(
                            "%c [ getExcelList ]-53",
                            "font-size:13px; background:pink; color:#bf2c9f;",
                            getExcelList
                        );
                        resolve(getExcelList);// 成功解析并处理Excel文件,返回getExcelList数组
                    } catch (e) {
                        reject(e);
                    }
                };
                // console.log('teacherUploadList', teacherUploadList);
                reader.readAsBinaryString(file);// 以二进制字符串形式读取上传的Excel文件内容,解析成功则调用reader.onload函数
            });
        }

你可能感兴趣的:(Vue.js学习,JavaScript实用小功能,前端,上传,下载文件,上传,导出.xlsx)