1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- /*
- * @Author: your name
- * @Date: 2025-04-28 14:46:54
- * @LastEditTime: 2025-05-06 10:15:08
- * @LastEditors: milo-MacBook-Pro.local
- * @Description: In User Settings Edit
- * @FilePath: /downLoadServer/src/server/controllers/uploadController.js
- */
- // src/server/controllers/uploadController.js
- import multer from "multer";
- import {
- uploadFileToMinIO,
- checkIfAFileExists,
- } from "../utils/minioService.js";
- import path from "path";
- import fs from "fs-extra";
- import { fileURLToPath } from "url";
- // 获取 __dirname
- const __filename = fileURLToPath(import.meta.url);
- const __dirname = path.dirname(__filename);
- // 设置 multer 存储
- const storage = multer.diskStorage({
- destination: (req, file, cb) => {
- cb(null, "uploads/"); // 上传文件的临时存储路径
- },
- filename: (req, file, cb) => {
- cb(null, file.originalname); // 使用原始文件名
- },
- });
- const upload = multer({ storage });
- // 上传文件的控制器
- export const uploadFile = async (req, res) => {
- const bucketName = req.body.bucketName; // 您的桶名称
- const filePath = req.body.filePath; // 从 req.body 中获取文件路径
- const objectName = req.body.objectName; // 在 MinIO 中的文件名
- // 检查 filePath 是否有效
- if (typeof filePath !== "string" || !filePath) {
- return res.status(400).json({ message: "Invalid file path" });
- }
- try {
- // 调用 uploadFileToMinIO 函数上传文件
- await uploadFileToMinIO(bucketName, filePath, objectName);
- // 构造文件的 URL
- const url = `http://${process.env.MINIO_ENDPOINT}:${process.env.MINIO_PORT}/${bucketName}/${objectName}`;
- // 删除临时文件
- if (filePath) {
- await fs.unlink(filePath);
- } else {
- console.error("filePath is undefined, cannot unlink");
- }
- res.status(200).json({ url, message: "File uploaded successfully" });
- } catch (error) {
- console.error("File upload failed:", error);
- res.status(500).json({ message: "File upload failed", error });
- }
- };
- export const uploadMiddleware = upload.single("file");
- export const checkIfAFileExistsInMinio = async (req, res) => {
- try {
- const bucketName = "bucket-zhzn"; // 您的桶名称
- const objectName = "1111.png"; // 在 MinIO 中的文件名
- const fileRes = await checkIfAFileExists(bucketName, objectName);
- console.log(fileRes, "fileRes");
- } catch (err) {}
- };
|