Utilizing API to Save Images Directly from the Client Side

I am currently in the process of redesigning a website, specifically the Blog section which includes a featured image. I have been researching the best method for saving these images.

After following a tutorial that utilized the file.mv() function from either mongoose or express (I believe), I was able to successfully move the images to a folder within my public directory while working on the development server. However, upon deploying to Heroku, the functionality ceased to work, likely due to file path inconsistencies.

I'm not certain if my approach is considered conventional, but essentially I allow blog writers to upload an image along with their post. The post content is then saved to my MongoDB database, with the file location stored under the featured image field rather than the entire image itself. This bypasses the need to store the image directly in the database.

If anyone has any advice on how to resolve this issue, it would be greatly appreciated! Thank you!

Below is the code snippet:

//save images
blogRouter.post('/upload', (req, res) => {
    if(req.files === null ){
        return res.status(400).json({ msg: 'No file uploaded'})
    }

    const file = req.files.file;
    const fileName = file.name.replace(/\s+/g, '');

    file.mv(`${__dirname}/../client/public/BlogImgs/${fileName}`, err => {
        if(err){
            console.error(err)
            return res.status(500).send(err);
        }

        res.json({ fileName: fileName, filePath: `/BlogImgs/${fileName}`});
    })
})

//Post New Blog
blogRouter.post('/', (req, res) => {
    let newBlog = new blog({
        title: req.body.title,
        content: req.body.content,
        author: req.body.author,
        comments: req.body.comments,
        featuredImg: req.body.featuredImg,
        summary: req.body.summary
    })
    newBlog.save().then(item => res.json(item))
})

Answer №1

Instead of saving it in your database, simply store the image's name and keep the actual image in a directory on your server. Consider utilizing multer for uploading images.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Tips for retaining input field content within a BootstrapVue table

Below is a BootstrapVue table I'm working with; https://i.sstatic.net/xu5Et.png The code, courtesy of this response, is showcased below; new Vue({ el: '#app', data() { return { filter: '', items: [ { i ...

Sending formdata containing a file and variables via $.ajax

I've been working on a jquery file upload project based on a tutorial I found here: . The tutorial is great and the functionality works perfectly. However, I'm looking to add more control and security measures for user image uploads, such as inco ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

Utilizing Vanilla JavaScript to retrieve information from a HTML table

I am currently running my website on XAMPP and I have a database connection set up that I can use. In my database, I have three drop-down menus labeled Translations, Books, and Chapters where the data for each is stored. My goal is to utilize Vanilla JS ...

JavaScript generated form fails to submit

I am currently facing an issue with submitting form data to a PHP file when it is generated using JavaScript. I am unsure of how to resolve this problem. The form submission works fine on a test .html file by itself, but not when it is generated by JavaScr ...

Transferring the bundle files of one Next.js app to another Next.js app

Currently, I manage two distinct Next.js applications that handle separate sets of routes. Additionally, I have developed a custom Next.js server that determines which page to display based on the requested URL. I am interested in utilizing the custom ser ...

What is the best way to save user session variables in a MEAN.JS application?

I have chosen to utilize MEAN.JS for my project. I need to save a parameter for each user throughout their session on the website (from when they first open the site until they close their browser, even if they do not log in). This parameter should be ac ...

Is the 'wait > remaining' condition ever satisfied in the throttle function of underscore.js?

Check out the library code at line 860: https://github.com/jashkenas/underscore/blob/master/underscore.js if (remaining <= 0 || remaining > wait) Under what circumstance would the second part of this statement be true? Background - This is my firs ...

Dynamic and operational icons accompany the AngularJS search input field

Currently, I am delving into the world of AngularJS and experimenting with a search box. Within this search box, I want to incorporate three icons: a magnifying glass, a cross, and a spinner. For the first scenario, I envision the magnifying glass appearin ...

Using Node.js and Angular to Access Google Spreadsheet JSON Data Across Different Origins

Seeking to extract JSON data from a public Google Spreadsheets page, my initial attempt involved an AJAX call which successfully retrieved the data but I struggled with saving it to my $scope. Switching to $http.get led me to encounter cross-origin reques ...

Guide for configuring Supabase authentication details in a NodeJS environment

I've decided to separate my Supabase database interactions from my client Flutter app and create a dedicated NodeJS express app for that purpose. Currently, I have included the credentials of the logged-in user in the header of my API requests as show ...

Dividing a pair of CSS stylesheets on a single HTML page

Currently, I am working on a HTML page that includes multiple javascripts and css files in the header section. <link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" /> In order to make the website mobile-friendly, I s ...

Make sure to execute a function prior to the ajax beforeSend

Before I upload a file using 'fileuploader', I attempted to check the file first in my beforeSend function: beforeSend: function(item, listEl, parentEl, newInputEl, inputEl) { var file = item.file; let readfile = functio ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Tips for handling tasks with javascript in mongodb

The Mongo database is set up with a sharding structure of 3 Shards named TestSharding. Additionally, the script for this configuration can be written in JavaScript. I am tasked with developing a program that identifies whether a file is in .json or .csv f ...

Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe. Please review the codesandbox json file first. The objective is to capture the total calories and nutritive c ...

Using JQuery and JavaScript to store and dynamically apply functions

I have a code snippet that looks like this:. var nextSibling = $(this.parentNode).next(); I am interested in dynamically changing the next() function to prev(), based on a keypress event. (The context here is an input element within a table). Can someo ...

When implementing dynamic routing in Next.js, an error occurs with TypeError: the 'id' parameter must be a string type. It is currently

I’m encountering a problem while creating dynamic pages in Next.js. I'm fetching data from Sanity and I believe my code is correct, but every time I attempt to load the page, I receive a type error - “the ‘id’ argument must be of type string. ...

Execute a function when a selection option is chosen consecutively two times

I have a dynamic dropdown menu that uses AJAX to load options. I need the function to be triggered not only when an option is changed, but also when the same option is clicked multiple times in a row. In other words, I want the function to run every time a ...