|
|
import express from "express"; |
|
|
import multer from "multer"; |
|
|
import sharp from "sharp"; |
|
|
import fs from "fs"; |
|
|
import path from "path"; |
|
|
|
|
|
const app = express(); |
|
|
const upload = multer({ dest: "/tmp/uploads" }); |
|
|
|
|
|
app.post("/convert", upload.single("file"), async (req, res) => { |
|
|
try { |
|
|
if (!req.file) { |
|
|
return res.status(400).send("No file uploaded"); |
|
|
} |
|
|
|
|
|
const originalName = path.parse(req.file.originalname).name; |
|
|
const outputFileName = `${originalName}.jpg`; |
|
|
const outputPath = path.join("/tmp", outputFileName); |
|
|
|
|
|
|
|
|
await sharp(req.file.path) |
|
|
.jpeg({ quality: 100, chromaSubsampling: "4:4:4" }) |
|
|
.toFile(outputPath); |
|
|
|
|
|
res.setHeader("Content-Type", "image/jpeg"); |
|
|
res.setHeader("Content-Disposition", `attachment; filename="${outputFileName}"`); |
|
|
|
|
|
const fileStream = fs.createReadStream(outputPath); |
|
|
fileStream.pipe(res); |
|
|
|
|
|
fileStream.on("close", () => { |
|
|
fs.unlinkSync(req.file.path); |
|
|
fs.unlinkSync(outputPath); |
|
|
}); |
|
|
|
|
|
} catch (error) { |
|
|
console.error(error); |
|
|
res.status(500).send("Conversion failed"); |
|
|
} |
|
|
}); |
|
|
|
|
|
const PORT = process.env.PORT || 7860; |
|
|
app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); |
|
|
|