feat: 导入导出与blob文件

master
LCJ-MinYa 2 months ago
parent d394ba1fdf
commit 7c9d012f7e

@ -0,0 +1,147 @@
## 怎么在控制台查看blob格式的内容
在浏览器控制台中查看 `Blob` 格式的内容,需要特别注意:**`Blob` 是二进制数据,不能像字符串一样直接打印**。如果你直接 `console.log(blob)`,控制台通常只会显示 `Blob { size: xxx, type: "..." }`,而不会显示内部的原始字节或可读内容。
---
## ✅ 正确方法:将 `Blob` 转成可读格式后查看
以下是 **在浏览器控制台中查看 Blob 内容的 5 种实用方式**,按推荐顺序排列:
---
### ✅ 方法 1`FileReader` 读取为文本(适用于文本类 Blob`.txt`, `.json`, `.html`
```js
// 假设你有一个 Blob 对象
const blob = new Blob(['Hello World'], { type: 'text/plain' });
// 使用 FileReader 读取为文本
const reader = new FileReader();
reader.onload = function (e) {
console.log('Blob 内容(文本):', e.target.result);
};
reader.readAsText(blob); // ✅ 重点readAsText
```
> ✅ 适合:`.txt`, `.json`, `.html`, `.xml` 等文本格式。
---
### ✅ 方法 2读取为 Base64 字符串(查看原始编码)
```js
const reader = new FileReader();
reader.onload = function (e) {
console.log('Blob 的 Base64 编码:', e.target.result);
};
reader.readAsDataURL(blob); // ✅ 读取为 data URL包含 base64
```
> ✅ 输出示例:
> ```
> data:text/plain;base64,SGVsbG8gV29ybGQ=
> ```
>
> - `data:` 协议 + `base64` 编码;
> - 可以复制粘贴到浏览器或工具中解码查看。
---
### ✅ 方法 3读取为 ArrayBuffer查看原始字节流
```js
const reader = new FileReader();
reader.onload = function (e) {
const arrayBuffer = e.target.result;
const uint8Array = new Uint8Array(arrayBuffer);
console.log('原始字节流Uint8Array:', uint8Array);
console.log('字节数组(前 20 个字节):', uint8Array.slice(0, 20));
};
reader.readAsArrayBuffer(blob); // ✅ 读取为 ArrayBuffer
```
> ✅ 输出示例:
> ```
> Uint8Array(11) [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
> ```
>
> - 每个数字是字节值ASCII 码);
> - 适合查看 PDF、Excel、图片等二进制文件的头部签名。
---
### ✅ 方法 4查看 Blob 的 `type``size`(基本信息)
```js
console.log('Blob 类型:', blob.type); // 如: 'application/pdf'
console.log('Blob 大小:', blob.size, '字节'); // 如: 12345
```
> ✅ 快速判断文件类型和大小。
---
### ✅ 方法 5`console.table()` 显示字节数组(更清晰)
```js
const reader = new FileReader();
reader.onload = function (e) {
const uint8Array = new Uint8Array(e.target.result);
const table = Array.from(uint8Array).map((byte, index) => ({
index,
byte,
hex: byte.toString(16).padStart(2, '0'),
char: String.fromCharCode(byte)
}));
console.table(table.slice(0, 20)); // 显示前 20 个字节
};
reader.readAsArrayBuffer(blob);
```
> ✅ 输出表格,清晰展示:
> - 字节索引、值、十六进制、ASCII 字符。
---
## 🔍 如何判断 Blob 是什么文件?
通过 `blob.type``arrayBuffer` 的前几个字节判断:
| 文件类型 | `blob.type` | 前 4 字节Hex | 说明 |
|----------|-------------|------------------|------|
| PDF | `application/pdf` | `25 50 44 46` | `%PDF` |
| Excel `.xlsx` | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` | `50 4B 03 04` | `PK`ZIP 格式) |
| Word `.docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | `50 4B 03 04` | 同上 |
| PNG 图片 | `image/png` | `89 50 4E 47` | `‰PNG` |
| JPEG 图片 | `image/jpeg` | `FF D8 FF E0` | `ÿØÿà` |
> ✅ 用 `new Uint8Array(arrayBuffer).slice(0, 4)` 查看前 4 字节即可快速识别。
---
## ✅ 常见错误写法(不要这样做)
```js
console.log(blob); // ❌ 只显示 Blob 对象,看不到内容
console.log(blob.toString()); // ❌ 返回 [object Blob],无意义
```
> ⚠️ 这些写法无法获取实际内容!
---
## ✅ 总结:查看 Blob 内容的正确流程
| 目标 | 推荐方法 |
|------|----------|
| 查看文本内容JSON、TXT | `readAsText(blob)` |
| 查看原始编码Base64 | `readAsDataURL(blob)` |
| 查看原始字节流 | `readAsArrayBuffer(blob)` + `Uint8Array` |
| 快速判断文件类型 | `blob.type` + 前 4 字节 |
| 清晰查看字节结构 | `console.table` + `Uint8Array` |
---
### ✅ 一句话总结:
> 🔍 **不能直接 `console.log(blob)` 查看内容**,必须使用 `FileReader` 读取为 `Text`、`DataURL` 或 `ArrayBuffer`,再转换为可读格式。
> ✅ 最推荐:用 `readAsArrayBuffer` + `Uint8Array` 查看原始字节,结合 `console.table` 更清晰。

@ -1,24 +1,51 @@
<template>
<el-card header="导入导出excel">
<h1>上传excel</h1>
<div class="flex">
<el-upload
style="width: 200px"
action="/excel/upload"
:headers="headers"
method="post"
:on-change="handleFileChange"
:on-remove="handleFileRemove"
:auto-upload="false"
:limit="1"
:file-list="fileList"
>
<el-button type="primary">上传excel</el-button>
<el-button type="primary">选择文件</el-button>
</el-upload>
<el-button
class="ml-5"
type="primary"
@click="uploadExcel"
>点击上传选中文件</el-button
>
</div>
<h1 class="mt-20">下载excel</h1>
<el-button
type="primary"
@click="downloadExcel"
>下载excel</el-button
>
</el-card>
<div
class="markdown-body"
v-html="htmlStr"
></div>
</template>
<script setup lang="jsx">
import { ref } from 'vue';
import Cookies from 'js-cookie';
import axios from 'axios';
import { marked } from 'marked';
import { getMarkdownContent } from '@/utils/tools';
const htmlStr = ref('');
getMarkdownContent('./md/importOrExportExcel.md').then((res) => {
htmlStr.value = marked(res);
});
defineOptions({
name: 'DemoImportOrExportExcel',
@ -28,10 +55,11 @@ const headers = ref({
Authorization: Cookies.get('Authorization') || '',
});
// excel(excel)
const downloadExcel = () => {
axios({
url: '/excel/download',
method: 'get',
method: 'post',
// responseTypeblob
responseType: 'blob',
headers: headers.value,
@ -39,13 +67,79 @@ const downloadExcel = () => {
const name = response.headers['content-disposition'].split(';')[1].split('=')[1];
// 'application/vnd.ms-excel;charset=utf-8'
let blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' });
let link = document.createElement('a');
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
link.setAttribute('download', name);
downloadBlobFile(blob, name);
// blobconsole.logblob
showBlobFile(blob);
});
};
// blob
const downloadBlobFile = (blob, fileName) => {
//
const downloanUrl = window.URL.createObjectURL(blob);
// a, a
const a = document.createElement('a');
a.style.display = 'none';
a.href = downloanUrl;
a.download = fileName;
// abodya
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// url
window.URL.revokeObjectURL(downloanUrl);
};
/*
* 提取一个公共打印blob文件的方法
* 发散思维如果是正常的文件那么这个文件可能很大
* 如果报错信息直接通过blob文件输出那我们应该怎么知道这个是报错的blob文件信息还是一个正常的文件信息
* 我们可以通过blob文件的大小size来判断
*/
const showBlobFile = (blob) => {
const reader = new FileReader();
reader.onload = (e) => {
console.log(e.target.result);
};
reader.readAsText(blob);
};
const fileList = ref([]);
const handleFileChange = (file, fileList) => {
console.log(file, fileList, '上传文件列表变化函数');
};
const handleFileRemove = (file, fileList) => {
console.log(file, fileList, '删除文件列表变化函数');
};
// excel(excel)
const uploadExcel = () => {
console.log(fileList);
// FormDatajson
// FormData
let formData = new FormData();
// filevalueblob
formData.append('file', fileList.value[0].raw);
// parmas1value(1)
formData.append('parms1', '我是其他参数1');
// parmas2value(2)
formData.append('parms2', '我是其他参数2');
// FormData
// let formData = new FormData();
// formData.append('file', fileList.value[0].raw);
// let parmam = {
// file: formData,
// parmam1: '1',
// parmam2: '2',
// }
axios({
url: '/excel/upload',
method: 'post',
data: formData,
headers: headers.value,
}).then((response) => {
console.log(response);
});
};
</script>

Loading…
Cancel
Save