John 8 月之前
父节点
当前提交
c781cc01a8
共有 5 个文件被更改,包括 100 次插入36 次删除
  1. 0 1
      epub_node/app.js
  2. 14 0
      epub_node/db/files.js
  3. 7 7
      epub_node/environment/index.js
  4. 50 28
      epub_node/router/epub/image.js
  5. 29 0
      epub_node/router/epub/index.js

+ 0 - 1
epub_node/app.js

@@ -77,6 +77,5 @@ app.use("/api/v1/epub", epub);
 // app.use("/api/v1/types", types);
 
 app.listen(port, () => {
-  console.log(`Example app listening on port ${port}`);
   logger.info(`Example app listening on port ${port}`)
 });

+ 14 - 0
epub_node/db/files.js

@@ -17,6 +17,7 @@ export async function files_insert({
   name = "",
   path = "",
 }) {
+  console.log(20, file_id, md5, mimetype, size, name, path)
   return new Promise(async (resolve, reject) => {
     try {
       const sql = `
@@ -32,3 +33,16 @@ export async function files_insert({
     }
   });
 }
+
+// 查询图片信息
+export function getFileBymd5(md5Str) {
+  return new Promise((resolve, reject) => {
+    connection.query(`SELECT * FROM files WHERE md5 = ?`, [md5Str], (err, rows) => {
+      if (err) {
+        resolve(false); // 如果存在记录,则返回 true,否则返回 false
+      } else {
+        resolve(rows[0]); // 如果存在记录,则返回 true,否则返回 false
+      }
+    });
+  });
+}

+ 7 - 7
epub_node/environment/index.js

@@ -1,12 +1,12 @@
 function dbInfo() {
   // 根据需要更新db的数据配置
-  return {
-    host: "localhost",
-    port: 3306,
-    user: "root",
-    password: "12345678",
-    database: "epub_manage",
-  };
+  // return {
+  //   host: "localhost",
+  //   port: 3306,
+  //   user: "root",
+  //   password: "12345678",
+  //   database: "epub_manage",
+  // };
   return {
     host: "192.168.2.101",
     port: 6806,

+ 50 - 28
epub_node/router/epub/image.js

@@ -1,82 +1,104 @@
+import { dirExists } from "#utils";
+import { files_insert } from "#db";
 import crypto from "crypto";
 import fs from "node:fs";
-import { files_insert } from "#db";
 
-export async function saveImgs(epub) {
+export async function saveImgs( epub ) {
   // const res = await Promise.allSettled(imgs.map(elm => {
   // }))
   let imgs = epub.listImage();
   console.log(imgs[0]);
-  console.log(imgs.length);
-  await epub.getImageAsync(imgs[0].id).then(async function ([data, mimeType]) {
+  console.log(1121, imgs.length);
+  await epub.getImageAsync(imgs[2].id).then(async function ( [data,mimeType] ) {
     console.log(`\ngetImage: cover\n`);
     console.log(data);
     const img_md5 = await calculateMD5FromBuffer(data);
     console.log(img_md5);
     console.log(mimeType);
-    console.log(1616, formatSize(data.length));
-    await files_insert()
+    console.log(1616,formatSize(data.length));
+    const params = {
+      file_id: img_md5,
+      md5: img_md5,
+      mimetype: mimeType,
+      size: data.length,
+      name: imgs[0].id,
+      path: imgs[0].href,
+    }
+
+    const uploadPath = "./base_files/" + img_md5;
+    dirExists("./base_files/");
+
+    // 如果需要将 JSON 保存为文件,可以使用 fs.writeFile()
+    fs.writeFile(uploadPath,data,( err ) => {
+      if ( err ) {
+        console.error("Error writing JSON file:",err);
+      } else {
+        console.log("JSON data saved to output.json");
+      }
+    });
+
+    await files_insert(params)
   });
 }
 
-function calculateMD5(filePath) {
+function calculateMD5( filePath ) {
   const hash = crypto.createHash("md5");
   const stream = fs.createReadStream(filePath);
 
-  stream.on("data", (chunk) => {
+  stream.on("data",( chunk ) => {
     hash.update(chunk);
   });
 
-  stream.on("end", () => {
-    console.log("MD5 hash:", hash.digest("hex"));
+  stream.on("end",() => {
+    console.log("MD5 hash:",hash.digest("hex"));
   });
 }
 
-export async function calculateMD5FromStream(fileStream) {
-  return new Promise((resolve, reject) => {
+export async function calculateMD5FromStream( fileStream ) {
+  return new Promise(( resolve,reject ) => {
     const hash = crypto.createHash("md5");
 
     // 错误处理
-    fileStream.on("error", (err) => {
-      console.error("Error reading file stream:", err);
+    fileStream.on("error",( err ) => {
+      console.error("Error reading file stream:",err);
       reject("生成失败!"); // 使用 reject 传递错误信息
     });
 
     // 监听 'data' 事件,更新 MD5 哈希
-    fileStream.on("data", (chunk) => {
+    fileStream.on("data",( chunk ) => {
       hash.update(chunk);
     });
 
     // 监听 'end' 事件,文件读取完毕后输出 MD5 值
-    fileStream.on("end", () => {
+    fileStream.on("end",() => {
       const md5 = hash.digest("hex");
-      console.log("MD5 Hash:", md5);
+      console.log("MD5 Hash:",md5);
       resolve(md5); // 正常计算完 MD5 后 resolve
     });
   });
 }
 
-export function calculateMD5FromBuffer(buffer) {
-  return new Promise((resolve, reject) => {
+export function calculateMD5FromBuffer( buffer ) {
+  return new Promise(( resolve,reject ) => {
     try {
       // 使用 crypto 计算 MD5
       const hash = crypto.createHash("md5");
       hash.update(buffer); // 直接更新 hash
 
       const md5 = hash.digest("hex"); // 获取最终的 MD5 值
-      console.log("MD5 Hash:", md5);
+      console.log("MD5 Hash:",md5);
       resolve(md5); // 返回 MD5
-    } catch (err) {
-      console.error("Error calculating MD5:", err);
+    } catch ( err ) {
+      console.error("Error calculating MD5:",err);
       reject("生成失败!");
     }
   });
 }
 
-const formatSize = (bytes) => {
-  if (bytes < 1024) return `${bytes} 字节`;
-  else if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
-  else if (bytes < 1024 * 1024 * 1024)
-    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
-  else return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
+const formatSize = ( bytes ) => {
+  if ( bytes < 1024 ) return `${ bytes } 字节`;
+  else if ( bytes < 1024 * 1024 ) return `${ ( bytes / 1024 ).toFixed(2) } KB`;
+  else if ( bytes < 1024 * 1024 * 1024 )
+    return `${ ( bytes / ( 1024 * 1024 ) ).toFixed(2) } MB`;
+  else return `${ ( bytes / ( 1024 * 1024 * 1024 ) ).toFixed(2) } GB`;
 };

+ 29 - 0
epub_node/router/epub/index.js

@@ -1,4 +1,8 @@
 // 添加账本
+import { getFileBymd5 } from "#db";
+import logger from "#logger";
+import path from "node:path";
+import fs from "node:fs";
 import express from "express";
 import { EPub } from "epub2";
 
@@ -18,6 +22,31 @@ router.get("/", async function (req, res) {
 router.get("/about", function (req, res) {
   res.send("About types");
 });
+
+router.get("/img/:fileId", async function (req, res) {
+  const fileId = req.params.fileId; // 获取 fileId 参数
+  logger.info(`Found ${fileId}`);
+  const fileRow = await getFileBymd5(fileId);
+
+  if (!fileRow) {
+    return res.status(404).send("文件查询失败");
+  }
+
+  const uploadPath = "./base_files/" + fileId;
+  console.log("uploadPath", uploadPath);
+  const filePath = path.resolve(uploadPath);
+  console.log("filePath", filePath);
+  // 检查文件是否存在
+  if (!fs.existsSync(filePath)) {
+    return res.status(404).send("服务器中不存在该文件");
+  }
+
+  // 返回文件
+  res.setHeader("Content-Type", fileRow.mimetype);
+  res.sendFile(filePath);
+});
+
+
 // define the about route
 router.put("/", async function (req, res) {
   let sampleFile;