uploadController.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * @Author: your name
  3. * @Date: 2025-04-28 14:46:54
  4. * @LastEditTime: 2025-05-06 10:15:08
  5. * @LastEditors: milo-MacBook-Pro.local
  6. * @Description: In User Settings Edit
  7. * @FilePath: /downLoadServer/src/server/controllers/uploadController.js
  8. */
  9. // src/server/controllers/uploadController.js
  10. import multer from "multer";
  11. import {
  12. uploadFileToMinIO,
  13. checkIfAFileExists,
  14. } from "../utils/minioService.js";
  15. import path from "path";
  16. import fs from "fs-extra";
  17. import { fileURLToPath } from "url";
  18. // 获取 __dirname
  19. const __filename = fileURLToPath(import.meta.url);
  20. const __dirname = path.dirname(__filename);
  21. // 设置 multer 存储
  22. const storage = multer.diskStorage({
  23. destination: (req, file, cb) => {
  24. cb(null, "uploads/"); // 上传文件的临时存储路径
  25. },
  26. filename: (req, file, cb) => {
  27. cb(null, file.originalname); // 使用原始文件名
  28. },
  29. });
  30. const upload = multer({ storage });
  31. // 上传文件的控制器
  32. export const uploadFile = async (req, res) => {
  33. const bucketName = req.body.bucketName; // 您的桶名称
  34. const filePath = req.body.filePath; // 从 req.body 中获取文件路径
  35. const objectName = req.body.objectName; // 在 MinIO 中的文件名
  36. // 检查 filePath 是否有效
  37. if (typeof filePath !== "string" || !filePath) {
  38. return res.status(400).json({ message: "Invalid file path" });
  39. }
  40. try {
  41. // 调用 uploadFileToMinIO 函数上传文件
  42. await uploadFileToMinIO(bucketName, filePath, objectName);
  43. // 构造文件的 URL
  44. const url = `http://${process.env.MINIO_ENDPOINT}:${process.env.MINIO_PORT}/${bucketName}/${objectName}`;
  45. // 删除临时文件
  46. if (filePath) {
  47. await fs.unlink(filePath);
  48. } else {
  49. console.error("filePath is undefined, cannot unlink");
  50. }
  51. res.status(200).json({ url, message: "File uploaded successfully" });
  52. } catch (error) {
  53. console.error("File upload failed:", error);
  54. res.status(500).json({ message: "File upload failed", error });
  55. }
  56. };
  57. export const uploadMiddleware = upload.single("file");
  58. export const checkIfAFileExistsInMinio = async (req, res) => {
  59. try {
  60. const bucketName = "bucket-zhzn"; // 您的桶名称
  61. const objectName = "1111.png"; // 在 MinIO 中的文件名
  62. const fileRes = await checkIfAFileExists(bucketName, objectName);
  63. console.log(fileRes, "fileRes");
  64. } catch (err) {}
  65. };