Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my database for future access. However, I'm currently facing an issue when it comes to displaying the uploaded file, specifically an image.

The files are saved in this manner: https://i.stack.imgur.com/0DahC.png

I'm uncertain about which path to store in my database. Should I save it as uploads/2e3546b428931124164022e5d1d9310e? Or do I need to include an extension?

The JSON object representation of the file is as follows:

{ fieldname: 'mapImage',
  originalname: 'office-wallpaper-2.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'uploads/',
  filename: '2e3546b428931124164022e5d1d9310e',
  path: 'uploads/2e3546b428931124164022e5d1d9310e',
  size: 736807 }

Answer №1

It's important to rename your file prior to uploading it. An effective method for accomplishing this is as follows

var storage = multer.diskStorage({
    destination: './public/uploads/',
    filename: function(req, file, cb) {
        crypto.pseudoRandomBytes(16, function(err, raw) {
            if (err) return cb(err);

            cb(null, raw.toString('hex') + path.extname(file.originalname));
        })
    }
})

var upload = multer({
    storage: storage
})

afterwards, store the filename in your database

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

Implementing dynamic URLs using static routing in Express

I'm looking for a way to render a page statically in Express that involves using a dynamic URL. For example, In my forum, users create posts and each post has its unique URL that shows the post when clicked: localhost:8080/posts/postNumber Current ...

Error: Module 'electron-prebuilt' not found

I am encountering an issue with my Electron app that utilizes Nightmare.js after compiling it into an .exe file using electron-packager. Everything functions properly until I click a button that triggers Nightmare.js, at which point I receive the followi ...

Display a hidden division when a radio button is selected using Javascript and Jquery

Currently, I am in the process of constructing a form that triggers a series of additional questions based on the selected answer. Below is my current working code snippet: $(".appliedWorked").click(function(){ if($(this).val()==="appliedWorkedYes") ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

Looking for a Javascript tool to select provinces graphically?

Looking for a graphic province selector similar to the one found on this website: . If anyone is aware of something like this, especially in the form of a jQuery plugin, that would be fantastic. Thank you. ...

Display numeric data when hovering over circles in the Google Maps API using Javascript

I recently implemented the Google Maps example code that displays a circle hovering over a city, with the size of the circle representing the population. I'm looking to enhance this feature by including numeric data display on mouseover as well. Any a ...

The art of swift JavaScript currency conversion based on time

I am in need of transforming a collection of data containing expenses with different dates into an alternative currency. One challenge is that these expenses cover multiple years, so I must consider the changes in exchange rates over time. Does anyone kno ...

Tips for deploying a React/Node application in a subdirectory

I am a beginner in React and Node.js development. I have successfully created an application that is currently running on a Linux server under the subdirectory named "abc". The app can be accessed through . However, I want it to run without the port number ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

What is the best way to run a callback once several Ajax requests have finished?

I am facing a challenge with executing a callback function after multiple jQuery Ajax requests have been completed. The issue arises when these Ajax requests call another function, resulting in the functions being undefined. I suspect that the root of ...

recording the results of a Node.js program in PHP using exec

I'm attempting to retrieve the output from my node.js script using PHP exec wrapped within an ajax call. I am able to make the call and receive some feedback, but I can't seem to capture the console.log output in the variable. This is how I exec ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...

`res.render when all data queries are completed``

When I make an app.get request in my server.js file, I retrieve a dataset from MongoDB and then render my page while passing the data to it. Here is an example: //page load app.get('/', (req, res) => { //find all data in test table ...

The dynamic Vue.js transitions and effects are like a magic

I am using a v-for to render multiple child components: <div v-for="(pass) in scoringPass" :key="pass.decision"> <Pass :pass="pass"/> </div> Each of these child components contains a transition tag: &l ...

Modifying the nested data organization in Sequelize

I'm looking to adjust the data structure retrieved from an ORM query involving four tables. The product and category tables have a many-to-many relationship, with the product_category table serving as a bridge. Additionally, there's a fourth tabl ...

JavaScript's ASYNC forEach function not following the expected sequence

I'm really struggling to understand the workings of async and await in this scenario. I want the forEach function to run before the console.log and res.json, but no matter what I do with async and await, it always ends up being the last thing executed ...

React Big Calendar - Creating a personalized property for a unique perspective

My React Big Calendar library has a custom view for the year. <Calendar localizer={localizer} events={events || []} startAccessor="start" endAccessor="end" defaultView="year" views={{ year: YearView }} c ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...