const express = require("express");
const multer = require("multer");
const port = 3000;
const app = express();
const cloudinary = require("cloudinary").v2;
const bodyParser = require("body-parser");
const fs = require("fs");
if (!fs.existsSync("./uploads")) {
fs.mkdirSync("./uploads");
}
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
var upload = multer({ storage: storage });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/public"));
app.use("/uploads", express.static("uploads"));
cloudinary.config({
cloud_name: "YOUR_CLOUD_NAME",
api_key: "YOUR_API_NAME",
api_secret: "YOUR_API_SECRET",
});
async function uploadToCloudinary(locaFilePath) {
var mainFolderName = "main";
var filePathOnCloudinary =
mainFolderName + "/" + locaFilePath;
return cloudinary.uploader
.upload(locaFilePath, { public_id: filePathOnCloudinary })
.then((result) => {
fs.unlinkSync(locaFilePath);
return {
message: "Success",
url: result.url,
};
})
.catch((error) => {
fs.unlinkSync(locaFilePath);
return { message: "Fail" };
});
}
function buildSuccessMsg(urlList) {
var response = `<h1>
<a href="/">Click to go to Home page</a><br>
</h1><hr>`;
for (var i = 0; i < urlList.length; i++) {
response += "File uploaded successfully.<br><br>";
response += `FILE URL: <a href="${urlList[i]}">
${urlList[i]}</a>.<br><br>`;
response += `<img src="${urlList[i]}" /><br><hr>`;
}
response += `<br>
<p>Now you can store this url in database or
`;
return response;
}
app.post(
"/profile-upload-single",
upload.single("profile-file"),
async (req, res, next) => {
var locaFilePath = req.file.path;
var result = await uploadToCloudinary(locaFilePath);
var response = buildSuccessMsg([result.url]);
return res.send(response);
}
);
app.post(
"/profile-upload-multiple",
upload.array("profile-files", 12),
async (req, res, next) => {
var imageUrlList = [];
for (var i = 0; i < req.files.length; i++) {
var locaFilePath = req.files[i].path;
var result = await uploadToCloudinary(locaFilePath);
imageUrlList.push(result.url);
}
var response = buildSuccessMsg(imageUrlList);
return res.send(response);
}
);
app.listen(port, () => {
console.log(`Server running on port ${port}!
\nClick http:
});