how to change the path where file is being uploaded in multer expressjs

Uploading Images to Cloudinary Using Multer and ExpressJS

Uploading Images to Cloudinary Using Multer and ExpressJS

upload file to Cloudinary with NodeJS
File upload has become a mutual feature in every web application, many tutorials yous'll find on the web will only show you how yous can upload files to your application's database and you get stuck when you lot're trying to upload your images to a cloud service like Cloudinary and Amazon S3. During the course of this tutorial, we'll be using Cloudiary for storing our images, we will then save the link to that epitome to our database instead of the entire prototype buffer.
In this article, I'll be showing what Cloudinary and Multer does and how like shooting fish in a barrel it is to work with them whether you're working on API for a Single Page Application, or building a monolithic awarding this tutorial got you covered.
Earlier we proceed, I've gear up up an empty ExpressJS application with support for ES6+ so that we can focus more on the file upload characteristic, you can access it from here.
Let's begin by first knowing the use of Cloudinary.
What is Cloudinary
Cloudinary is an cease-to-end epitome direction solution for your website and mobile apps. Cloudinary covers everything from prototype uploads, storage, manipulations, optimizations to delivery.
You lot tin easily upload images to the cloud, automatically perform smart image manipulations without installing whatever complex software. All your images are then seamlessly delivered through a fast CDN, optimized and using manufacture all-time practices.
Cloudinary offers comprehensive APIs and assistants capabilities and is piece of cake to integrate with new and existing spider web and mobile applications.
You tin can learn more than about cloudinary here
To get started, create/sign to your Cloudinary account, on your dashboard you should run across your account details like this.

on your Cloudinary dashboard
On the root directory of your application, there's a sample.env file that contains all the environment variables we'll exist using for this application. You should encounter something similar this.
Create a .env file on the root directory of your application, copy all the variable names and replace the values with your Cloudinary info.
Permit's install the Cloudinary parcel that volition permit united states to interface with the Cloudinary API npm install cloudinary.
At present to cease up the Cloudinary setup process, On your server/ directory, create a config/ folder, and a file named cloudinaryConfig.js. This directory will contain the configuration you'll demand to upload files to Cloudinary. When you're washed, your directory should now look like this.

On the cloudinaryConfig.js file, configure the parcel to utilise our Cloudinary credentials with the block of code below.
import { config, uploader } from 'cloudinary';
const cloudinaryConfig = () => config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: procedure.env.CLOUDINARY_API_SECRET,
});
export { cloudinaryConfig, uploader };
Great!!! Cloudinary has been set up successfully on your application, we can now go along to upload files with the aid of multer.
What Is Multer?
npm i multer
Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on height of busboy for maximum efficiency.
Why Is Needed?
Out of the box, NodeJS doesn't know how to process any data, for example, nosotros wanted our application to process JSON requests, we had to body-parse, in this case, multer makes it possible for an application to accept class-data which allows usa to hands transport files from the browser to our server.
multer
Middleware for handling multipart/form-information.
world wide web.npmjs.com
Without multer, when yous're sending a files to your server, the request body object(req.body) will exist empty. Multer allows the data y'all're sending from a class to be available and it also creates a req.file object which gives us access to the file buffer we've just uploaded from the client-side.
Now let's configure Multer as a middleware that we can apply with any route that needs to upload an image. On the middleware folder, create a multer.js file with the following configuration.
import multer from 'multer';
const storage = multer.memoryStorage();
const multerUploads = multer({ storage }).unmarried('prototype');
consign { multerUploads };
Find that we're making use of retentivity storage instead beginning writing the file to an upload/ directory, this is considering when we deploy our awarding to Heroku, we may non have the adminitrative privileges to write files to the remote computer which may crash our entire application.
multer.memoeryStorage() tells multer that we'll save the file to retentivity commencement which tin exist manipulated to the suit any purpose.
multer({ storage }).single('image'); sets the storage choice we'll be using on the application while the .single('epitome'); specifies the field name multer should get to when it's looking for the file.
Now it's all fix, allow's try to utilise multer and Cloudinary to upload an image.
Import multerUploads on your server/index.js and add the post-obit block of code to your server/alphabetize.js file
app.postal service('/upload', multerUploads, (req, res) => {
panel.log('req.body :', req.trunk);
});
Now open postman on the trunk section, select forma-data and enter the field proper noun you used in your multer configuration which in our case was image. Your postman should look like this, now click on send.

Detect it logs an empty object on the console.

Now on the fieldname "image", change the blazon textto file just as in the screenshot to a higher place, you should accept something similar to this.

On the upload route, modify console.log('req.body :', req.body); to console.log('req.file : ' req.file); go dorsum to postman, and select an image, striking the send button and you lot should take something similar this

Congratulations multer is now working equally a middleware, we can go ahead and employ it on our entire awarding, but for the sake of this article, we'll only call multer on the routes we need it.
But I desire to you to observe that the file is coming as buffer because nosotros're pushing information technology to memory before we can upload information technology to Cloudinary, which pose an outcome for us since the Cloudinary uploader is either expecting a file path or a string but we're receiving a buffer from multer.
So permit'south convert the buffer to the format that the Cloudinary uploader will understand, we're going to use thedatauri package.
What Is a Information URI?
A data URI is a base64 encoded cord that represents a file. Getting the contents of a file as a string ways that yous can straight embed the data within your HTML or CSS lawmaking. When the browser encounters a data URI in your code, information technology's able to decode the data and construct the original file. Learn more
npm i datauri to add the parcel and and then update your multer setup to look similar this.
import multer from 'multer';
import Datauri from 'datauri';
import path from 'path';
const storage = multer.memoryStorage();
const multerUploads = multer({ storage }).single('image');
const dUri = new Datauri();
/**

  • @description This function converts the buffer to data url
  • @param {Object} req containing the field object
  • @returns {String} The information url from the string buffer
    /
    const dataUri = req => dUri.format(path.extname(req.file.originalname).toString(), req.file.buffer);
    export { multerUploads, dataUri };
    On the dataUri function in a higher place, we pass the request object and format the buffer and return a string blob.
    It's time to add the Cloudinary uploader to the awarding, but start permit's brand some modification on the configuration function, it's best we convert it to a middleware then that we don't take to invoke it everytime we want to use the Cloudinary settings.
    Your new Cloudinary config should await be like this.
    import { config, uploader } from 'cloudinary'
    import dotenv from 'dotenv';
    dotenv.config();
    const cloudinaryConfig = (req, res, next) => {
    config({
    cloud_name: procedure.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET,
    });
    side by side();
    }
    export { cloudinaryConfig, uploader };
    Notice I added a new parcel called dotenv it allows us load the settings on our .env file into the node application process.
    npm i dotenv , update your server/alphabetize.js to look similar this.
    import express from 'express';
    import { urlencoded, json } from 'body-parser';
    import { resolve } from 'path';
    import { uploader, cloudinaryConfig } from './config/cloudinaryConfig'
    import { multerUploads, dataUri } from './middlewares/multerUpload';
    const app = express();
    const Port = process.env.PORT || 3000;
    app.use(limited.static(resolve(__dirname, 'src/public')));
    app.employ(urlencoded({ extended: simulated }));
    app.employ(json());
    app.use('
    ', cloudinaryConfig);
    app.become('/*', (req, res) => res.sendFile(resolve(__dirname, '../public/index.html')));
    app.post('/upload', multerUploads, (req, res) => {
    if(req.file) {
    const file = dataUri(req).content;
    render uploader.upload(file).then((result) => {
    const image = effect.url;
    return res.status(200).json({
    messge: 'Your image has been uploded successfully to cloudinary',
    data: {
    image
    }
    })
    }).catch((err) => res.condition(400).json({
    messge: 'someting went incorrect while processing your request',
    information: {
    err
    }
    }))
    }
    });
    app.listen(Port, () => console.log(Server started at http://localhost:${Port}));
    Open postman once again, select a file and click ship yous should become this message

you can now relieve the prototype URL to your database.
Congratulations, y'all merely learn how to upload files to Cloudinary using multer.
I hope this was helpful, please exit your thoughts in the comment section below.
Link to this repo

Notice and read more posts from Jehonadab Okpukoro

stpierrehorce1986.blogspot.com

Source: https://www.codementor.io/@joejackson045/uploading-images-to-cloudinary-using-multer-and-expressjs-zthuy53oi

0 Response to "how to change the path where file is being uploaded in multer expressjs"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel