47 lines
1.7 KiB
JavaScript
47 lines
1.7 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
const express_1 = require("express");
|
|
const multer_1 = __importDefault(require("multer"));
|
|
const path_1 = __importDefault(require("path"));
|
|
const uuid_1 = require("uuid");
|
|
const auth_1 = require("../middleware/auth");
|
|
const router = (0, express_1.Router)();
|
|
const storage = multer_1.default.diskStorage({
|
|
destination: (req, file, cb) => {
|
|
cb(null, 'uploads/');
|
|
},
|
|
filename: (req, file, cb) => {
|
|
const ext = path_1.default.extname(file.originalname);
|
|
cb(null, `${(0, uuid_1.v4)()}${ext}`);
|
|
}
|
|
});
|
|
const upload = (0, multer_1.default)({
|
|
storage,
|
|
limits: { fileSize: 10 * 1024 * 1024 },
|
|
fileFilter: (req, file, cb) => {
|
|
const allowedTypes = /jpeg|jpg|png|gif|webp/;
|
|
const extname = allowedTypes.test(path_1.default.extname(file.originalname).toLowerCase());
|
|
const mimetype = allowedTypes.test(file.mimetype);
|
|
if (extname && mimetype) {
|
|
return cb(null, true);
|
|
}
|
|
cb(new Error('Only image files are allowed'));
|
|
}
|
|
});
|
|
router.post('/upload', auth_1.authenticate, upload.single('photo'), (req, res) => {
|
|
try {
|
|
if (!req.file) {
|
|
return res.status(400).json({ error: 'No file uploaded' });
|
|
}
|
|
const url = `/uploads/${req.file.filename}`;
|
|
res.json({ url });
|
|
}
|
|
catch (error) {
|
|
console.error('Upload error:', error);
|
|
res.status(500).json({ error: 'Failed to upload file' });
|
|
}
|
|
});
|
|
exports.default = router;
|