transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code:

let express = require('express');
let im = require('imagemagick');
let gm = require("gm").subClass({
    imageMagick: true
});
let multer  = require('multer');

let app = express();

let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
});
var upload = multer({storage: storage}).single('avatar');

app.post('/', function (req, res) {
    upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
            res.json({
                success: false,
                message: 'error during uploading'
            });
        } else if (err) {
            res.json({
                success: false,
                message: 'error during uploading'
            });
        }

        res.json({
            success: true,
            message: 'Image uploaded'
        });
    })
})

app.listen(3000);

Upon sending a post request with a file in form-data, I receive a success message, but the directory to store the file is not created:

post request

EDIT:

I have successfully uploaded the file by modifying the path to the uploads directory in the code like this:

let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
});

However, the uploads directory needs to be manually created as it is not automatically generated when missing... How can I resolve this issue?

Answer №1

To resolve this issue, take a look at the following link: https://github.com/expressjs/multer/issues/287

According to the information provided, it is recommended to create a directory in the 'destination' folder beforehand.

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

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

Adjust the translateX value and element size based on either the parent element's size or the window's dimensions

Is this question specific enough to relate to others' problems? My issue involves two elements, a child and a parent, with the child element rotating around the parent using CSS animations. <div class="planet"> <div class="moon"></di ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

Nuxt js - Components are replicated on SSR pages

I have created a static page containing various components. When I navigate to this page from another page, everything displays correctly. However, when I directly land on the page, some components are duplicated and rendered again after the footer. Upon i ...

Retrieving width and height of the content block inner in Framework7, excluding navbar and toolbar dimensions

Is there a reliable way to determine the width and height of the page content-block-inner, excluding the navbar and toolbar? This measurement can vary across different devices and operating systems. I attempted to assign an id to the content-block-inner a ...

Tips for sending data through AJAX before the browser is about to close

My issue is with a javascript function that I've called on the html unload event. It seems to be working fine in Google Chrome, but for some reason it's not functioning properly in Firefox and IE. <script> function fun() { ...

Enhancing Redux efficiency with substantial data structures

I have developed a web application using Redux and React. It is an analytics application that displays a significant amount of data. However, I am facing performance issues as the size of my data store increases. What is the best approach to prevent perfo ...

In Angular 5 and Node Express, a fresh session is initialized for every individual request made

I'm currently working on a project using Angular 5 to connect to my NodeJS server. After the user logs in, I store their information in the req.session object. However, when I attempt to make another request from the Angular 5 app to access the API, ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

The front end is failing to display error messages generated on the server side

When the server-side login fails, the message res.status(403).json({ fail: "Login failed" }); is passed to the frontend using setHelperText(failMessage);. How can I display the 'Login Failed' message on the frontend? An error is displayed in the ...

Tips for maximizing the efficiency of a callback when utilizing the filter function in Primefaces for 'myDataTable'

Currently using Primefaces 5.1, and I've encountered a situation where I want to hide a table until after the filter is applied in Javascript. My initial thought was to simply set the css of the table to visibility:hidden;, followed by running the fol ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner: {"3": {"label":"All i want for christmas", "song":"Alliw_1405399165.mp3", "name":"All i want for christmas"}, "4": {"label":"Call your girlfriend robyn clip", "song":"Gang ...

Conflicting Joomla Modules

I'm currently working on a project at the following link: www.eltotaldesign.com/planeteco Within this project, I have integrated the modules DJ Image Slider and Altra Switcher. Despite attempting to install Easy JQuery and other methods, I have been ...

The issue with the jQuery class change not being triggered in Internet Explorer seems to be isolated, as Chrome and

This little jQuery script I have is supposed to show a fixed navigation menu once the page has been scrolled below 200px, and then change the class on each menu list item to "current" when that section reaches the top of the viewport. The issue is that th ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...