Using Node.js to upload images and store their URLs in MySQL database

I have a Node.js application that allows users to upload images, which are then stored in a directory named uploads.

My goal is to save the image URLs in a MySQL database and display all the uploaded images using HTML.

To handle image uploads, I am utilizing the formidable module.

app.get('/upload', function (req, res){
    res.sendFile(__dirname + '/index.html');
});

app.post('/up', function (req, res){
    var form = new formidable.IncomingForm();

    form.parse(req);

    form.on('fileBegin', function (name, file){
        file.path = __dirname + '/uploads/' + file.name;
    });

 form.on('file', function (name, file) {
        console.log('Uploaded ' + file.name);

        connection.query('SELECT * FROM images', (err, results) => {
            // Throw error if find function fails
            if (err) return (new Error(err));

            // Throw error if there is already a file with that name
            if (results[0]) return (new Error('File with that name already exists, please choose another name'));

            connection.query('INSERT INTO images', (error, results) => {


                // Throw error if save function fails
                if (err) return (new Error(err));

                // Throw error if you cannot verifty the save occured.

                if (results.affectedRows !== 1) return (new Error('There was an unexpected error. Please try again'));
                // Send Log to signal successfull upload
                console.log('Uploaded ' + file.name);
            });
        });
    });
});
 

Answer №1

To easily save the image URL in this function, you can follow this approach:

form.on('file', function (name, file){
     console.log('Uploaded ' + file.name);
});

If you are using a database connection, the syntax may resemble the following example:

form.on('file', function (name, file){
    database.find({file: file.path}, (err, result) => {
        // Handle error if find function fails
        if(err) return(new Error(err));

        // Handle error if a file with the same name already exists
        if(result) return(new Error('File with that name already exists, please choose another name'));

        database.save({file: file.path}, (err, result) => {
            // Handle error if save function fails
            if(err) return(new Error(err));

            // Handle error if it's unable to verify the save operation
            if(result.count !== 1) return(new Error('There was an unexpected error. Please try again'));

            // Log success message for upload
            console.log('Uploaded ' + file.name);
        });
    });
});

EDIT #1:

In MySQL, the process would be similar to this:

form.on('file', function (name, file){
    connection.query('SQL SELECT QUERY HERE', (err, results) => {
        // Handle error if find function fails
        if(err) return(new Error(err));

        // Handle error if a file with the same name already exists
        if(results[0]) return(new Error('File with that name already exists, please choose another name'));

        connection.query('SQL INSERT QUERY HERE', (error, results) => {
            // Handle error if save function fails
            if(err) return(new Error(err));

            // Handle error if it's unable to verify the save operation
            if(results.affectedRows !== 1) return(new Error('There was an unexpected error. Please try again'));

            // Log success message for upload
            console.log('Uploaded ' + file.name);
        });
    });
});

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

When using npm install, nested dependencies may not be installed automatically. However, you can explicitly install them to

In my custom package located at https://github.com/Voitanos/jest-preset-spfx, I have specified the following dependencies: "dependencies": { "@types/jest": "28.1.4", "identity-obj-proxy": "3.0.0", &qu ...

Unable to verify credentials for accessing the MongoDB database on localhost

Recently, I embarked on a new project using Express and decided to utilize MongoDB as my database due to Node.js being the backend technology. This is my first time working with Mongo, and although I can authenticate successfully from the terminal, I' ...

The Yeoman tool is experiencing functionality issues on Windows operating systems

After installing Node version 0.10.4 and npm 1.2.18 on a Windows 64-bit system, I attempted to install Yeoman by using 'npm install -g yo'. However, the installation was unsuccessful as the 'yo' command is not recognized on my machine. ...

Enhance the readability and writability of the properties of JavaScript objects

I'm curious if there's a way to make existing properties of JavaScript objects immutable after they've been assigned. Essentially, what I want is to lock in the current properties of an object but still allow new ones to be added. Can exis ...

How can I download a PDF file in React.js using TypeScript on Next.js?

I've created a component to download a PDF file. The PDF file is named resumeroshan.pdf and it's located inside the Assets folder. "use client"; import resume from "/../../Assets/resumeroshan.pdf"; export default function Abo ...

Using Node.js on Heroku

I've set up my basic nodejs server on Heroku, but unfortunately I'm encountering this error when trying to access it: Application error - An error occurred in the application and your page could not be served. If you are the application owner, ...

The zlib.gunzipSync function is not supported in Node.js when using the meteorhacks:npm package

I recently encountered an issue while using meteorhacks:npm to import the npm module Telegram.link in Meteor. Everything seemed to be working fine until I attempted to call a specific function, which resulted in the following error message: W20160218-16:3 ...

Leveraging jQuery Ajax and MySQL to generate dynamic HTML content

I'm in the process of creating a unique photo gallery that utilizes dynamic features. Instead of relying on constant HTML/PHP refreshing for updates, I am incorporating jQuery to handle dynamic MYSQL queries. As a beginner, I've managed to creat ...

NPM - dependencies necessitate the package to be in numerous versions, yet only a single version is actually installed

Upon executing npm install in a fresh environment, I encountered an issue with the b package: npm ls b <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f5d4a6baa4baa2">[email protected]</a> ├── <a hr ...

Seeking assistance for my dissertation assignment: electron, express, and SQLite3

I am currently dedicated to my thesis project, which involves designing an educational desktop video game for both public and private schools within my city. Being a fan of electron, I thought it would be a great idea to develop my app using this platform ...

Saving a PDF file in Node.js using Express and Multer

Currently, I am utilizing a multer api to save files in memory. This is necessary because I have a requirement to upload both images and pdf files, with the added need to process the images. So far, I am able to successfully upload images, however, I am e ...

An error was encountered while attempting to proxy the request [HPM]

After cloning a GitHub repository, I ran npm i in both the root directory and client directories. I then created a development configuration file. However, when attempting to run npm run dev, nodemon consistently crashes with a warning about compiled cod ...

Cross-Origin Resource Sharing using Express.js and Angular2

Currently, I am attempting to download a PLY file from my Express.js server to my Angular/Ionic application which is currently hosted on Amazon AWS. Here is the Typescript code snippet from my Ionic app: //this.currentPlyFile contains the entire URL docum ...

Node.js is known for its unreliable promise returns

Currently, I have a function in place that establishes a connection with a sql database. After querying the database and formatting the results into an HTML table, the function returns the variable html: function getData() { return new Promise((resolv ...

There was an error during product validation that occurred in the userId field. In the Node.js application, it is required to

I am in the process of developing a small shop application using node.js, express, and mongoose. However, I have encountered an issue when attempting to send data to the MongoDB database via mongoose. Here is the product class I have created: const mongoo ...

Ways to obtain a SHA1 hash for a blob block in Azure storage using Node.js without the need to download the file

Can someone assist me with code sample for file validation using sha-1 hash in Node.js? I am looking to obtain the sha-1 hash value without downloading the block from azure storageblob. // Example of uploading BlockBlob using @azure/storage-blob npm bloc ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...

Foundation-sites module missing - new project requires installation of Node modules

I recently encountered an issue that has been discussed multiple times here, but unfortunately, I couldn't find a suitable solution. After formatting my disk and installing macOS Monterey, the following software versions were installed: node.js v16. ...

"Discover the issue with the conversation query not functioning properly in Sequelize's

I've been grappling with this issue for several days now - trying to determine if there is a conversation existing between two users using Sequelize. I have established relationships between conversation, message, user, and userConversations. Below is ...

Error message: "An internal server issue occurred while attempting to upload an image in base64 format via AWS Lambda

I've been working on uploading images to S3 using AWS Lambda. I found some helpful code in a URL and made some modifications to the variables fileFullPath and Bucket: Upload Image into S3 bucket using Api Gateway, Lambda funnction const AWS = requir ...