文件工具函数
2024/9/11大约 5 分钟
本文档整理了常用的文件处理工具函数。
浏览器端文件下载
实现代码
/**
* 下载文件
* @param fileUrl 文件URL
* @param fileName 文件名
*/
async function downloadFile(fileUrl, fileName) {
try {
// 发送HTTP GET请求获取文件内容
const response = await fetch(fileUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 将响应体转换为Blob对象
const blob = await response.blob();
// 创建用于下载的链接元素
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
// 如果未提供文件名,则尝试从响应头中获取
if (!fileName) {
const contentDisposition = response.headers.get("content-disposition");
if (contentDisposition) {
const match = contentDisposition.match(/filename="?([^"]*)"?/);
if (match) {
fileName = match[1];
}
}
// 如果仍然没有文件名,则使用默认文件名
fileName = fileName || "downloaded_file";
}
// 设置下载文件名
a.download = fileName;
// 触发下载操作
document.body.appendChild(a);
a.click();
// 清理资源
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error("Error downloading file:", error);
}
}
代码解析
该函数用于在浏览器环境中下载文件,主要步骤如下:
- 发送请求:使用
fetch
API 发送 HTTP GET 请求获取文件内容。 - 响应检查:检查响应状态,非 200 状态则抛出错误。
- Blob 转换:将响应体转换为 Blob 对象,便于后续处理。
- 创建下载链接:使用
URL.createObjectURL
创建临时 URL,并创建<a>
元素。 - 文件名处理:优先使用提供的文件名,否则尝试从响应头的
content-disposition
中提取,最后使用默认文件名。 - 触发下载:设置
<a>
元素的download
属性并触发点击事件。 - 资源清理:释放临时 URL 并移除创建的元素。
- 错误处理:使用
try...catch
捕获并记录可能的错误。
使用方法
// 基本使用
// 下载PDF文件并指定文件名
downloadFile("https://example.com/file.pdf", "document.pdf");
// 下载图片文件
downloadFile("https://example.com/image.jpg");
// 下载文本文件
downloadFile("https://example.com/data.txt", "data-2024.txt");
// 在实际应用中,可能需要处理加载状态
const downloadButton = document.querySelector("#download-button");
downloadButton.addEventListener("click", async () => {
downloadButton.disabled = true;
downloadButton.textContent = "下载中...";
try {
await downloadFile("https://example.com/large-file.zip", "archive.zip");
} finally {
downloadButton.disabled = false;
downloadButton.textContent = "下载";
}
});
Node.js 环境下保存网络图片
实现代码
import fs from "fs";
import path from "path";
import https from "https";
/**
* 保存图片到本地
* @param {string} imgPath 图片保存路径
* @param {string} imgName 图片名称
* @param {string} imgUrl 图片地址
*/
function saveImage(imgPath, imgName, imgUrl) {
const fullPath = imgPath + imgName;
// 创建目录
try {
if (!fs.existsSync(fullPath)) {
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
}
} catch (error) {
console.log("创建目录失败", error);
return;
}
https
.get(imgUrl, function (res) {
let imgData = "";
res.setEncoding("binary");
res.on("data", function (chunk) {
imgData += chunk;
});
res.on("end", function () {
try {
fs.writeFileSync(fullPath, imgData, "binary");
console.log("保存图片成功", fullPath);
} catch (err) {
console.log("保存图片失败", err.message);
}
});
})
.on("error", function (err) {
console.error("请求图片时发生错误:", err.message);
});
}
代码解析
该函数用于在 Node.js 环境中下载并保存网络图片,主要步骤如下:
- 路径处理:组合图片保存路径和图片名称,得到完整的文件路径。
- 目录创建:检查并递归创建所需的目录结构。
- 图片请求:使用 Node.js 的
https.get
方法请求网络图片。 - 数据处理:设置编码为 "binary",并监听 "data" 事件累积图片数据。
- 文件写入:在 "end" 事件触发时,将累积的图片数据以二进制格式写入文件。
- 错误处理:捕获并记录目录创建、图片请求和文件写入过程中可能发生的错误。
使用方法
// 基本使用
// 保存单个图片
saveImage("./images/", "example.jpg", "https://example.com/image.jpg");
// 保存多个图片
const imagesToSave = [
{
path: "./photos/landscape/",
name: "mountain.jpg",
url: "https://example.com/mountain.jpg",
},
{
path: "./photos/portrait/",
name: "person.jpg",
url: "https://example.com/person.jpg",
},
{
path: "./photos/animal/",
name: "cat.jpg",
url: "https://example.com/cat.jpg",
},
];
imagesToSave.forEach((item) => {
saveImage(item.path, item.name, item.url);
});
// 注意:Node.js 版本要求为 22.12.0 或更高
Electron 应用中下载图片文件
实现代码
const { dialog } = require("electron");
const fs = require("fs");
const https = require("https");
const { basename, join } = require("path");
/**
* 下载图片文件
* @param args 包含图片URL的参数对象
* @param event Electron事件对象
* @returns {Promise<{data:boolean, msg:string}>}
*/
async function downloadImg(args, event) {
const imageUrl = args.imageUrl; // 假设图片URL通过args传递
if (!imageUrl) {
console.error("[error] Image URL is required");
return { data: false, msg: "图片URL为空" };
}
// 获取图片名称
const imageName = basename(new URL(imageUrl).pathname);
const options = {
title: "Save file",
defaultPath: join("D:/", imageName),
buttonLabel: "保存",
filters: [
{ name: "Images", extensions: ["jpg", "png", "gif"] },
{ name: "All Files", extensions: ["*"] },
],
properties: ["saveFile"],
};
try {
const { filePath } = await dialog.showSaveDialog(null, options);
if (filePath) {
const result = await downloadFile(imageUrl, filePath);
if (result) {
console.log("[info] File saved successfully!");
return { data: true, msg: "保存成功" };
} else {
console.error("[error] File save failed!");
return { data: false, msg: "保存失败" };
}
} else {
return { data: false, msg: "取消保存" };
}
} catch (err) {
console.error("[error]" + err);
return { data: false, msg: "保存失败" };
}
}
/**
* 下载文件
* @param url 文件URL
* @param filePath 保存路径
* @returns {Promise<boolean>}
*/
function downloadFile(url, filePath) {
return new Promise((resolve, reject) => {
https
.get(url, (response) => {
if (response.statusCode !== 200) {
console.error(
`[error] Failed to get '${url}' (${response.statusCode})`
);
return reject(false);
}
const fileStream = fs.createWriteStream(filePath);
response.pipe(fileStream);
fileStream.on("finish", () => {
fileStream.close();
console.log("File saved successfully!");
resolve(true);
});
fileStream.on("error", (err) => {
fs.unlink(filePath, () => {}); // 删除已创建的文件
console.error(`[error] Error downloading file: ${err.message}`);
reject(false);
});
})
.on("error", (err) => {
console.error(`[error] Error downloading file: ${err.message}`);
reject(false);
});
});
}
代码解析
该函数集用于在 Electron 应用中下载图片文件,主要组件包括:
downloadImg 函数:
- 接收包含图片 URL 的参数对象和 Electron 事件对象
- 验证图片 URL 是否存在
- 从 URL 中提取图片名称
- 使用
dialog.showSaveDialog
显示保存文件对话框 - 根据用户选择调用
downloadFile
函数下载文件 - 返回下载结果(成功/失败状态和消息)
downloadFile 函数:
- 接收文件 URL 和保存路径
- 返回 Promise 对象用于异步处理
- 使用 Node.js 的
https.get
请求文件 - 通过管道(pipe)将响应流直接写入文件
- 处理下载完成、错误等事件
- 在下载失败时删除已创建的文件
使用方法
// 在Electron主进程中使用
const { ipcMain, app, BrowserWindow } = require("electron");
// 创建窗口后设置IPC通信
ipcMain.handle("download-image", downloadImg);
// 在渲染进程中调用(通过IPC)
// renderer.js
const { ipcRenderer } = require("electron");
document.querySelector("#download-btn").addEventListener("click", async () => {
const imageUrl = document.querySelector("#image-url").value;
const result = await ipcRenderer.invoke("download-image", { imageUrl });
if (result.data) {
alert(result.msg); // 显示"保存成功"
} else {
alert(result.msg); // 显示错误或取消消息
}
});
// 注意:Electron 版本要求为 21.4.4 或兼容版本
更新日志
2025/9/28 09:03
查看所有更新日志
38e56
-于