xb18
xb18
文章78
标签0
分类0
File相关

File相关

File相关

File 对象继承自 Blob 对象

1
2
<input type='file' id="fileItem"/>
var file = document.getElementById('fileItem').files[0];// 可以多个文件

文件下载fetch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<a href="result.png" download>download</a>
<a href="test.png" download="joker.png">下载</a>

// fetch
function downloadFile(url, filename='') {
fetch(url, {
headers: new Headers({
Origin: location.origin,
}),
mode: 'cors',
})
.then(res => res.blob())
.then(blob => {
const blobUrl = window.URL.createObjectURL(blob)
download(blobUrl, filename)
window.URL.revokeObjectURL(blobUrl)
})
}
function download(href, filename = '') {
const a = document.createElement('a')
a.download = filename
a.href = href
document.body.appendChild(a)
a.click()
a.remove()
}

文件下载axios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function downloadExcel(endpoint, filename) {
axios.get(endpoint, {
responseType: 'blob' // 指定响应类型为 blob,以便处理二进制文件
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename); // 设置下载文件的名称
link.style.display = 'none'; // 确保链接不可见

// 触发下载
document.body.appendChild(link);
link.click();

// 清理资源
window.URL.revokeObjectURL(url);
document.body.removeChild(link);
})
.catch((error) => {
// 根据实际情况处理错误,例如显示一个错误消息给用户
console.error("Error downloading Excel file:", error);
alert('An error occurred while downloading the Excel file. Please try again later.');
});
}

// 使用函数下载Excel文件
downloadExcel('/path/to/your/excel/endpoint', 'filename.xlsx');

在JavaScript中,new Blob([response.data]) 是用来创建一个新的 Blob 对象的语法。Blob 对象表示一段不可变的原始数据,它可以是任何类型的数据,通常用于处理文件和二进制数据。

在这个特定的上下文中,response.data 是Axios从HTTP响应中接收到的数据。当Axios请求的 responseType 被设置为 'blob' 时,response.data 将包含一个 Blob 对象,这个对象包含了响应主体中的二进制数据。

然而,有时候后端服务器可能直接发送二进制数据,而前端Axios在接收到这些数据时,即使设置了 responseType: 'blob'response.data 也已经是二进制数据了。在这种情况下,直接将这些数据包装在一个新的 Blob 对象中可能是必要的,以确保数据以正确的格式被处理。

通常,如果你已经设置了Axios的 responseType'blob',并且服务器正确响应了二进制数据,那么你不需要再次创建一个新的 Blob 对象。你可以直接将 response.data 用作 Blob 对象

保存文本txt

1
2
3
4
5
6
7
8
9
10
11
const downloadText = (text, filename = '') {
const a = document.createElement('a')
a.download = filename
const blob = new Blob([text], {type: 'text/plain'})
// text指需要下载的文本或字符串内容
a.href = window.URL.createObjectURL(blob)
// 会生成一个类似blob:http://localhost:8080/d3958f5c-0777-0845-9dcf-2cb28783acaf 这样的URL字符串
document.body.appendChild(a)
a.click()
a.remove()
}
1
2
3
4
5
6
7
8
9
10
11
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: false,
clientX: 100,
clientY: 100,
ctrlKey: true,
shiftKey: false
});

element.dispatchEvent(clickEvent);
本文作者:xb18
本文链接:https://moelj.com/2024/08/16/File%E7%9B%B8%E5%85%B3/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可