Skip to content

Let's use AI to Earn!

ele 下载文件操作

DESKTOP-ZTS2NQJNA62007d60feca
diff --git a/electron/main/index.ts b/electron/main/index.ts
index 9fdbc9bd..5cc51686 100644
--- a/electron/main/index.ts
+++ b/electron/main/index.ts
@@ -10,6 +10,7 @@ import { getAssetPath } from '../util/index';
import windowOperate from '../util/windowOperate';
import { logger } from '../global/log';
import { SplashWindow } from './splash';
+import { registerFileHandlers } from './ipc/fileHandler';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -125,6 +126,9 @@ app.whenReady().then(async () => {
update(bWin);
views(bWin);
windowOperate.init(bWin);
+
+ // 注册文件处理IPC
+ registerFileHandlers();
} catch (error) {
logger.error('Failed to start application:', error);
app.quit();
diff --git a/electron/main/ipc/fileHandler.ts b/electron/main/ipc/fileHandler.ts
new file mode 100644
index 00000000..d147352d
--- /dev/null
+++ b/electron/main/ipc/fileHandler.ts
@@ -0,0 +1,19 @@
+/**
+ * 文件处理IPC
+ */
+import { ipcMain } from 'electron';
+import { downloadFileToTemp } from '../utils/fileDownloader';
+
+// 注册IPC处理程序
+export function registerFileHandlers() {
+ // 下载文件到临时目录
+ ipcMain.handle('download-file-to-temp', async (_, url: string, fileType: 'video' | 'image') => {
+ try {
+ const filePath = await downloadFileToTemp(url, fileType);
+ return { success: true, filePath };
+ } catch (error) {
+ console.error('下载文件失败:', error);
+ return { success: false, error: error.message };
+ }
+ });
+}
\ No newline at end of file
diff --git a/electron/main/utils/fileDownloader.ts b/electron/main/utils/fileDownloader.ts
new file mode 100644
index 00000000..7847f419
--- /dev/null
+++ b/electron/main/utils/fileDownloader.ts
@@ -0,0 +1,62 @@
+/**
+ * 文件下载工具
+ * 在Electron主进程中实现文件下载功能
+ */
+import { app } from 'electron';
+import * as fs from 'fs';
+import * as path from 'path';
+import axios from 'axios';
+import { v4 as uuidv4 } from 'uuid';
+
+/**
+ * 从网络URL下载文件到本地临时目录
+ * @param url 文件URL
+ * @param fileType 文件类型 'video' | 'image'
+ * @returns 本地文件路径
+ */
+export const downloadFileToTemp = async (url: string, fileType: 'video' | 'image'): Promise<string> => {
+ try {
+ // 获取应用数据目录
+ const userDataPath = app.getPath('userData');
+ const tempDir = path.join(userDataPath, 'temp');
+
+ // 确保临时目录存在
+ if (!fs.existsSync(tempDir)) {
+ fs.mkdirSync(tempDir, { recursive: true });
+ }
+
+ // 生成唯一文件名
+ const fileExtension = fileType === 'video' ? '.mp4' : '.jpg';
+ const fileName = `${uuidv4()}${fileExtension}`;
+ const filePath = path.join(tempDir, fileName);
+
+ // 下载文件
+ const response = await axios({
+ method: 'GET',
+ url: url,
+ responseType: 'stream',
+ timeout: 60000, // 60秒超时
+ });
+
+ // 创建写入流
+ const writer = fs.createWriteStream(filePath);
+
+ // 将响应数据写入文件
+ response.data.pipe(writer);
+
+ return new Promise((resolve, reject) => {
+ writer.on('finish', () => {
+ console.log(`文件已下载到: ${filePath}`);
+ resolve(filePath);
+ });
+
+ writer.on('error', (err) => {
+ console.error('文件写入失败:', err);
+ reject(err);
+ });
+ });
+ } catch (error) {
+ console.error('文件下载失败:', error);
+ throw error;
+ }
+};
\ No newline at end of file
diff --git a/package.json b/package.json
index 8aae8db7..27df388a 100644
--- a/package.json
+++ b/package.json
@@ -49,6 +49,7 @@
"events": "^3.3.0",
"ffprobe-static": "^3.1.0",
"fluent-ffmpeg": "^2.1.3",
+ "fs": "^0.0.1-security",
"image-size": "^1.2.0",
"lodash": "^4.17.21",
"mime-types": "^2.1.35",
diff --git a/src/icp/file.ts b/src/icp/file.ts
new file mode 100644
index 00000000..c0551008
--- /dev/null
+++ b/src/icp/file.ts
@@ -0,0 +1,46 @@
+/**
+ * 文件操作IPC接口
+ */
+import { message } from 'antd';
+import axios from 'axios';
+
+/**
+ * 从网络URL下载文件到本地临时目录
+ * @param url 文件URL
+ * @param fileType 文件类型 'video' | 'image'
+ * @returns 本地文件路径或URL
+ */
+export const icpDownloadFileToTemp = async (url: string, fileType: 'video' | 'image'): Promise<string> => {
+ try {
+ // 检查是否支持IPC
+ if (window.electron?.ipcRenderer) {
+ // 使用Electron IPC
+ const result = await window.electron.ipcRenderer.invoke('download-file-to-temp', url, fileType);
+
+ if (!result.success) {
+ throw new Error(result.error || '下载失败');
+ }
+
+ return result.filePath;
+ } else {
+ // 浏览器环境下,直接返回URL
+ // 验证URL是否可访问
+ try {
+ const response = await axios.head(url);
+ if (response.status === 200) {
+ console.log('URL可访问,直接使用原始URL');
+ return url;
+ }
+ } catch (error) {
+ console.warn('URL访问检查失败,继续使用原始URL', error);
+ }
+
+ return url;
+ }
+ } catch (error) {
+ console.error('文件下载失败:', error);
+ message.error('文件下载失败,使用原始URL继续');
+ // 出错时返回原始URL
+ return url;
+ }
+};
\ No newline at end of file
diff --git a/src/utils/fileUtils.ts b/src/utils/fileUtils.ts
deleted file mode 100644
index b2a0a528..00000000
--- a/src/utils/fileUtils.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * 文件工具函数
- */
-import { message } from 'antd';
-import { v4 as uuidv4 } from 'uuid';
-
-/**
- * 从网络URL下载文件到本地临时目录
- * @param url 文件URL
- * @param fileType 文件类型 'video' | 'image'
- * @returns 本地文件路径或Blob URL
- */
-export const downloadFileToLocal = async (url: string, fileType: 'video' | 'image'): Promise<string> => {
- try {
- // 使用代理服务器解决跨域问题
- const proxyUrl = `/api/proxy?url=${encodeURIComponent(url)}`;
-
- // 下载文件
- const response = await fetch(proxyUrl, {
- mode: 'cors',
- credentials: 'same-origin'
- });
-
- if (!response.ok) {
- throw new Error(`下载失败: ${response.status} ${response.statusText}`);
- }
-
- // 获取文件内容
- const blob = await response.blob();
-
- // 创建Blob URL
- const blobUrl = URL.createObjectURL(blob);
-
- return blobUrl;
- } catch (error) {
- console.error('文件下载失败:', error);
- message.error('文件下载失败,请重试');
- throw error;
- }
-};
-
-/**
- * 使用视频元素加载视频URL
- * @param videoUrl 视频URL
- * @returns Promise<string> 视频URL
- */
-export const loadVideoUrl = (videoUrl: string): Promise<string> => {
- return new Promise((resolve) => {
- // 直接返回原始URL,依赖视频元素自身的加载能力
- resolve(videoUrl);
- });
-};
-
-/**
- * 使用图片元素加载图片URL
- * @param imageUrl 图片URL
- * @returns Promise<string> 图片URL
- */
-export const loadImageUrl = (imageUrl: string): Promise<string> => {
- return new Promise((resolve) => {
- // 创建图片元素预加载
- const img = new Image();
- img.crossOrigin = 'anonymous'; // 尝试解决跨域问题
- img.onload = () => resolve(imageUrl);
- img.onerror = () => {
- console.warn('图片加载失败,使用原始URL');
- resolve(imageUrl);
- };
- img.src = imageUrl;
- });
-};
-
-/**
- * 从网络URL下载文件并保存到本地
- * @param url 文件URL
- * @param filename 保存的文件名
- */
-export const downloadAndSaveFile = async (url: string, filename: string): Promise<void> => {
- try {
- // 创建一个a标签
- const a = document.createElement('a');
- a.href = url;
- a.download = filename;
- a.target = '_blank'; // 在新窗口打开,避免跨域问题
- a.style.display = 'none';
-
- // 添加到DOM并触发点击
- document.body.appendChild(a);
- a.click();
-
- // 清理
- setTimeout(() => {
- document.body.removeChild(a);
- }, 100);
-
- // 等待用户完成下载
- return new Promise((resolve) => {
- // 给用户足够的时间保存文件
- setTimeout(resolve, 3000);
- });
- } catch (error) {
- console.error('保存文件失败:', error);
- message.error('保存文件失败,请重试');
- throw error;
- }
-};
\ No newline at end of file
diff --git a/src/views/task/components/videoInfo.tsx b/src/views/task/components/videoInfo.tsx
index 6af2436f..3745f505 100644
--- a/src/views/task/components/videoInfo.tsx
+++ b/src/views/task/components/videoInfo.tsx
@@ -26,7 +26,7 @@ import {
LoadingOutlined
} from '@ant-design/icons';
import ChooseAccountModule from "@/views/publish/components/ChooseAccountModule/ChooseAccountModule";
-import { downloadAndSaveFile } from '@/utils/fileUtils';
+import { icpDownloadFileToTemp } from '@/icp/file';
const FILE_BASE_URL = import.meta.env.VITE_APP_FILE_HOST;
@@ -105,23 +105,14 @@ const Com = forwardRef<TaskInfoRef>((props: any, ref) => {
console.log('下载视频:', videoUrl);
console.log('下载封面:', coverUrl);
- // 使用下载链接触发浏览器下载
- message.info('请在弹出的窗口中保存视频文件');
- await downloadAndSaveFile(videoUrl, `视频任务_${taskInfo.id}.mp4`);
+ // 使用IPC接口下载视频文件到本地临时目录
+ const localVideoPath = await icpDownloadFileToTemp(videoUrl, 'video');
- message.info('请在弹出的窗口中保存封面图片');
- await downloadAndSaveFile(coverUrl, `封面_${taskInfo.id}.jpg`);
+ // 使用IPC接口下载封面图片到本地临时目录
+ const localCoverPath = await icpDownloadFileToTemp(coverUrl, 'image');
- // 提示用户输入保存的文件路径
- const localVideoPath = prompt('请输入视频文件保存的完整路径:', '');
- if (!localVideoPath) {
- throw new Error('未提供视频文件路径');
- }
-
- const localCoverPath = prompt('请输入封面图片保存的完整路径:', '');
- if (!localCoverPath) {
- throw new Error('未提供封面图片路径');
- }
+ console.log('视频已下载到:', localVideoPath);
+ console.log('封面已下载到:', localCoverPath);
message.destroy();
message.success('文件下载完成,开始发布...');
@@ -138,7 +129,6 @@ const Com = forwardRef<TaskInfoRef>((props: any, ref) => {
// 创建二级记录
for (const vData of aList) {
const account = vData.account!;
- const video = vData.video!;
await icpCreateVideoPubRecord({
type: account.type,