How to upload a PDF Document on Cloudinary - node.js

I am trying to upload a PDF document on Cloudinary through a node.js server.
The current approach I am using is inadequate and doesn't work.
I will appreciate if anyone can proffer a solution to this problem that works, thank you.
Cloudinary Storage Configuration:
const cloudinary = require("cloudinary").v2,
{ CloudinaryStorage } = require("multer-storage-cloudinary");
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
folder: "<some_folder>",
allowedFormats: ["jpg", "png", "pdf"],
});
module.exports.store = storage;
Image Upload Route:
const express = require("express"),
router = express.Router(),
cors = require("cors"),
fileUploadController = require("../../../controllers/haulage/users/fileUploadController");
const authenticate = require("../../../auth/auth"),
multer = require("multer"),
storage = require("../../../../config/cloudinary").store,
parser = multer({ storage: storage });
router
.route("/images")
.put(
authenticate,
cors(),
parser.array("image"),
fileUploadController.uploadImage
);
module.exports = router;
Image Upload Controller:
exports.uploadImage = async (req, res) => {
try {
const events = JSON.parse(JSON.stringify(req.files));
const urls = [];
events.map((e) => {
const url = e.path;
urls.push(url);
});
res.status(201).json({ URLS: urls });
} catch {
res.status(500).json({ error: "Server Error, Image Failed to Add" });
}
};

Are you part of the free plan in Cloudinary? If yes, it might be related to this issue: https://support.cloudinary.com/hc/en-us/articles/360016480179-Why-does-my-pdf-link-isn-t-working-
If not, can you please elaborate on the issue? where do you see the error?
The code to upload pdf ( same as any image):
var cloudinary = require('cloudinary')
cloudinary.v2.uploader.upload("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",function(res,err){console.log(res,err)});

Related

how do I receive an image that I've uploaded to my server using multer and nodejs in my angular app?

Please I'm new to Nodejs and I'm trying to create an image uploader that will upload files to my server using Nodejs and multer, but the problem is in getting the image back to be displayed in my angular app.
This is the backend code:
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const app = express();
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200,
}
app.use(cors(corsOptions));
app.use(express.static('uploads'));
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads");
},
filename: function (req, file, cb) {
cb(null, `${Date.now()}_${file.originalname}`);
},
})
const upload = multer({ storage });
app.post('/file', upload.single('file'), (req, res) => {
const file = req.file;
if (file) {
res.json(file);
} else {
throw new Error('File upload unsuccessful')
}
})
const port = 3000;
app.listen(port, () => console.log(`Server running on port ${3000}`));
This is my app.html code:
<input type="file" name="image" (change)="upload($event)">
This is my app.ts code:
upload(event: any) {
const file = event.target.files[0];
const formdata = new FormData();
formdata.append('file', file)
this.httpClient.post('http://localhost:3000/file', formdata)
.subscribe((data) => {
console.log(data);
},
(error) => {
console.log(error)
})
Please help me retrieve the image so that I can use it in my angular app. Thank you.
There are two ways you can achieve this. Both the approaches have their own pros and cons.
Store the image locally and send the URL back to the browser.
if (req.files) {
const fileNames = [];
for (let i = 0; i < req.files.length; i++) {
const file = req.files[i];
const relPath = "your/img/path";
const dirName = path.join(BASE_APP_PATH, relPath);
const relFileName = path.join(
relPath,
`${i + 1}_${file.originalname.replace(",", "")}`
);
const img_location = `${dirName}/${
i + 1
}_${file.originalname}`;
if (!fs.existsSync(dirName)) fs.mkdirSync(dirName, { recursive: true });
fs.writeFileSync(img_location, file.buffer, {});
fileNames.push(relFileName);
}
}
Get the image and send back base64 to the browser.
const encoded = req.files[0].buffer.toString('base64')

Retrieivng image from DB using multer

I am working on MERN application and I am facing issue in displaying the image.Using multer, the image path store in the MongoDB after file uploaded successfully and the image also stores in the folder "uploads", but there is problem I am getting while retrieving the image path from db.
all the text data retrieved but displaying image give me error.
Error I got:
CANNOT GET http://localhost:3000/uploads/image-1614468761737.jpg
Here is the code.
const express = require("express")
const path = require("path")
const route = express.Router()
const Post = require("../models/postModel")
const multer = require("multer")
const storage = multer.diskStorage({
destination(req,file,cb){
cb(null,"uploads/")
},
filename(req,file,cb){
cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storage,
filefilter: function(req,file,cb) {
const filetypes = /jpg|jpeg|png/
const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimetype = filetypes.test(file.mimetype)
if(extname && mimetype){
return cb(null, true)
}else{
cb(null,false)
}
},
})
route.post("/upload",upload.single("image"),(req,res)=>{
const file = req.file.path.replace(/\\/g,"/" )
res.send(`/${file}`)
})
route.post("/", async(req,res)=>{
const post = req.body
try {
const createpost = new Post(post)
await createpost.save()
res.status(200).json(createpost)
} catch (error) {
res.status(404).json({msg:"create post failed"})
}
})
module.exports = route
in the main file I also add
app.use("/uploads",express.static(path.join(__dirname,"/uploads")))
file structure:
file structure and uploads folder is in the root
GitHub:
https://github.com/mozi47/Check-error

Uploading multiple files to Google Cloud using multer and Node.js

I am trying to upload multiple files to Google Cloud bucket using Node.js and multer. It works with multer.single function but I don't know how to upload multiple images at once.
const bucket = gc.bucket('still-cover');
// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
storage: Multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
},
});
Router.post('/test/upload',multer.array('files',5),async(req,res)=>{
if (!req.files) {
res.status(400).send('No file uploaded.');
return;
}
// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(req.files.originalname);
const blobStream = blob.createWriteStream();
blobStream.on('finish', res => {});
blobStream.on('finish', () => {
// The public URL can be used to directly access the file via HTTP.
const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`
res.status(200).send(publicUrl);
});
blobStream.end(req.files.buffer);
});
You can use multer.array('files', numberoffiles) or multer.any()to upload files to your Google Cloud Storage Bucket. You can use the following code to upload multiple files using Multer:
const express = require('express');
const path = require('path');
const cors = require('cors');
const Multer = require('multer');
const bodyParser = require('body-parser');
const {Storage} = require('#google-cloud/storage');
// Creates a client
const storage = new Storage();
const bucket = storage.bucket('YOUR_BUCKET_NAME')
const PATH = './public/';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
const multer = Multer({
storage: Multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
},
});
app.get('/', function(req, res){
res.json({
json: "json"
});
})
// You can also use multer.array('data', numberofFiles)
app.post('/', multer.any(), function(req, res) {
console.log(req.files);
var counter = 0;
if (!req.files) {
res.status(400).send('No file uploaded.');
return;
}
// Create a new blob in the bucket and upload the file data.
req.files.forEach((fil) => {
const blob = bucket.file(fil.originalname);
const blobStream = blob.createWriteStream();
blobStream.on('finish', () => {
counter+=1
// The public URL can be used to directly access the file via HTTP.
const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`
if(counter>=2){
res.status(200).send(publicUrl);
}
});
blobStream.end(req.files.buffer);
});
});
app.listen(3000, function () {
console.log("Working on port 3000");
});
On the line blobStream.end(req.files.buffer); replace files.buffer with fil.buffer.

TypeError cloudinary is not a function

I dont know what Im doing wrong, I use the same code for another project and I did not have any problem with cloudinary
const cloudinary = require('cloudinary').v2;
const cloudinaryStorage = require('multer-storage-cloudinary');
const multer = require('multer');
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET,
});
var storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: 'recipe',
allowedFormats: ['jpg', 'png'],
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const uploadCloud = multer({ storage: storage });
module.exports = uploadCloud;
You can use the below code to solve this issue.
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const express = require('express');
const multer = require('multer');
const app = express();
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'some-folder-name',
format: async (req, file) => 'png', // supports promises as well
public_id: (req, file) => 'computed-filename-using-request',
},
});

How to add location path to Mysql DB with using Multer in Node.JS

I'm new in Node.JS development. Recently I've struggling that problem: I want to upload photo to in "/uploads" directory in my project. I've added photo alone. But when its come to adding photo server and save its location path with photos owner id and description to Mysql DB I didn't make it. I know that Multer only accept multipart-form data.
Here is my Node.Js code
var models = require('../../models');
var express = require('express');
var router = express.Router();
var multer = require('multer');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:'50mb'}));
app.use(bodyParser.urlencoded({extended:true, limit:'50mb'}));
const uuidv1 = require('uuid/v1');
var owner_id;
var description;
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
const photo_id = uuidv1();
cb(null, photo_id + '.jpg');
addPhotoToDb(photo_id,owner_id,description);
}
});
function addPhotoToDb(photo_id,owner_id,description) {
models.PHOTOS.create({
photo_id: photo_id,
description: description,
owner_id: owner_id,
location_path: 'uploads/' + photo_id + '.jpg'
})
}
var upload = multer({ storage: storage }).single('photo');
router.post('/upload', function (req, res) {
//This part is problematic I tried so many things
//owner_id=req.files
//description=req.files
upload(req, res, function (err) {
if (err) {
}
res.json({
success: true,
message: 'Image uploaded!'
});
})
});
module.exports = router;
Also in Postman I'm sending request like that:
https://i.stack.imgur.com/04Qz1.png
In your screenshot you show the "body" tab. In the left there is the "headers" tab. Click on it and check that you have the content-type set to "multipart/form-data" because multer won't process any data that aren't on this content type.

Resources