Skip to content

Let's use AI to Earn!

feat: 文件下载

牛文政ac8e9631e207
diff --git a/electron/main/tools/controller.ts b/electron/main/tools/controller.ts
index 4e5fa4a3..316f6298 100644
--- a/electron/main/tools/controller.ts
+++ b/electron/main/tools/controller.ts
@@ -28,7 +28,7 @@ export class ToolsController {
}
/**
- * 视频截取指定时间点的帧
+ * 下载文件
*/
@Icp('ICP_TOOL_DOWN_FILE')
async downFile(
@@ -36,8 +36,12 @@ export class ToolsController {
url: string,
name?: string,
): Promise<string> {
- const res = await FileUtils.downFile(url, name);
- console.log('-----', res);
- return '';
+ try {
+ const res = await FileUtils.downFile(url, name);
+ return res;
+ } catch (error) {
+ console.log('--- ICP_TOOL_DOWN_FILE error ---', error);
+ return '';
+ }
}
}
diff --git a/electron/util/file.ts b/electron/util/file.ts
index d828449e..e99aa769 100644
--- a/electron/util/file.ts
+++ b/electron/util/file.ts
@@ -4,6 +4,7 @@ import ffmpeg from 'fluent-ffmpeg';
import { ffprobePath } from './ffprobe_static';
import path from 'path';
import { net } from 'electron';
+import { v4 as uuidv4 } from 'uuid';
// 文件工具类
// 设置 ffprobe 路径
@@ -270,23 +271,35 @@ export class FileUtils {
*/
static async downFile(url: string, name?: string): Promise<string> {
const dirPath = this.getAppDataPath();
- console.log('------- dirPath', dirPath);
-
await this.checkDirectories(dirPath);
return new Promise((resolve, reject) => {
const request = net.request(url);
let fileStream: NodeJS.WritableStream | null = null;
let filePath: string;
+ const fileExt: string = path.extname(url);
request.on('response', (response) => {
if (response.statusCode !== 200) {
return reject(new Error(`下载失败: 状态码 ${response.statusCode}`));
}
- filePath = path.join(dirPath, name || 'default_filename.mp4');
+ filePath = path.join(dirPath, (name || uuidv4()) + fileExt);
fileStream = fs.createWriteStream(filePath);
+ response.on('data', (chunk) => {
+ if (fileStream) fileStream.write(chunk);
+ });
+
+ fileStream.on('finish', () => {
+ resolve(filePath);
+ });
+
+ // 处理文件流错误
+ fileStream.on('error', (err) => {
+ reject(err);
+ });
+
response.on('end', () => {
if (fileStream) {
fileStream.end();
diff --git a/src/views/reply/index.tsx b/src/views/reply/index.tsx
index ce1f1786..a3f4c9e6 100644
--- a/src/views/reply/index.tsx
+++ b/src/views/reply/index.tsx
@@ -22,7 +22,7 @@ export default function Page() {
async function downFile() {
const res = await ipcDownFile(
'https://ai-to-earn.oss-cn-beijing.aliyuncs.com/development/temp/nopath/202503/f1cffb9c-c42a-4fcc-8516-0e2c276ee2f8.mp4',
- '111',
+ 'default_filename',
);
console.log('----- res', res);
}