文件工具函数
2024年9月11日大约 2 分钟
下载文件
/**
* 下载文件
* @param fileUrl 文件URL
* @param fileName 文件名
*/
async function downloadFile(fileUrl: string, fileName?: string): Promise<void> {
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);
}
}
保存网络图片到本地(Node.js)
Node.js 版本为:22.12.0
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);
});
}
下载图片文件(Electron)
Electron 版本为:21.4.4
const {dialog} = require('electron');
const fs = require('fs');
const https = require('https');
const {basename, join} = require("path");
/**
* 下载图片文件
* @param args
* @param event
* @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 this.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
* @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);
});
});
}