Saving a file with its original filename using ng file upload on the server: Tips and tricks

I am having an issue with ng file upload where my files are being saved on the server with a different file name. I want them to be saved with their original file name and correct extension (.jpg, .pdf). Here is my code snippet. Controller:

$scope.uploadPic = function (file) {
         $scope.advert.userDetails={
        "name":userDetails.name,
        "email":userDetails.email,
        "role":userDetails.role
    }
        file.upload = Upload.upload({
            url: '/api/uploaders/uploads',
            method: 'POST',
            fields: {
                details: $scope.advert
            },
            file: file,
            fileFormDataName: 'photo'
        });

    file.upload.then(function (response) {
        console.log("Postcontroller: upload then ");
        $timeout(function () {
            file.result = response.data;
        });
    }, function (response) {
        if (response.status > 0)
            $scope.errorMsg = response.status + ': ' + response.data;
    });

    file.upload.progress(function (evt) {
        // Math.min is to fix IE which reports 200% sometimes
        file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
        console.log("PostController: upload progress " + file.progress);
    });
            file.upload.success(function (data, status, headers, config) {
        // file is uploaded successfully
        console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
        console.log(data);
    });

}

Api:

var multer = require('multer');
var upload = multer({ dest: 'server/uploads/images'});

Answer №1

It's actually multer, not ng-upload, that changes the filename for security reasons.
To prevent users from potentially executing malicious files by knowing their exact path, the filename is altered.

If you really insist on keeping the original filename, you can adjust your API like this:

var multer = require('multer');

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

var upload = multer(storage);

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

"Encountered an issue while trying to find the Node.js installation directory" error message appeared during npm install

Every time I try to run npm install or install anything using Node (like nvm) in any terminal (or even within Visual Studio Code), I encounter a consistent error message: node:net:404 err = this._handle.open(fd); ^ Error: EISDIR ...

Issue: ENOENT - The specified file or directory, './views/s.ejs', does not exist in Node.js Express

Encountering an error when attempting to render a file from the 'views' directory in the 'routes'. The specific error message is as follows: Error: Valid Login { [Error: ENOENT: no such file or directory, open './views/s ...

Deactivate the node-xmpp client

I have been exploring the functionalities of node-xmpp and node-simple-xmpp in order to create a basic client. Everything seems to be working well, except for the disconnection. Following the example from simple-xmpp, I have created the following file: ...

Issue debugging with express-generator project in vscode

In an effort to improve my development speed, I decided to enhance my debugging skills in Visual Studio Code. I had been following the guidance provided in the vsCode documentation but encountered a roadblock. I utilized Express (v4.16.0) to create a basi ...

What is the best way to mimic a directive's $scope variable?

I am working with a directive that has the following structure: angular.module('myApp', []) .directive('myDirective', ['$window', function($window){ return { link: function(scope, element, attr, controller) { ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

How can we utilize the transformRequest feature to convert a string into a functional output while making an $http.get

I am currently facing an issue with my web app when sending an $http.get request. The response is a plain-text string that looks like "Hello!" instead of JSON format. I do not want to make changes to the back-end, so I am exploring options to modify the tr ...

What is the process for setting a dynamic layout in a Jade template for Node.js/Express 3.0?

Having some trouble with setting the layout for my index.jade file. I have layoutA.jade, layoutB.jade and index.jade and want to programmatically choose which layout index.jade will extend. I attempted to use this code: app.set('view options', ...

The combination of Angular2, TypeScript, and moment.js is lacking in terms of available locales (only 'en' is supported)

Currently, I am following a tutorial in a book to grasp the concepts of TypeScript and AngularJS 2.0:(Become_a_Ninja_with_Angular2). In one section, the tutorial walks through creating a custom Pipe and demonstrates an implementation using moment.js. To ...

NodeJS Server - Implementing Configurations for Multiple URL Rewrites

Seeking to utilize a NodeJS server as a quick fix to test some AngularJS apps that were developed in a .NET environment (running on a mac). Both applications make use of the <base> tag and have rewrite rules in the web.config file to prevent 404 erro ...

Update the AngularJS (1.5) application to Angular 5

Looking for advice on transitioning an AngularJS app to Angular (in this case, version 5). I've been exploring the official documentation, but I still have some uncertainties. From what I gathered in the guide, it suggests migrating from AngularJS by ...

Despite my specifying an HTTP registry, NPM continues to use HTTPS

My NPM project is configured to use a self-hosted NPM registry in Nexus. I need to access this repository via HTTP (unable to change this requirement), but no matter what steps I take, the resolved URL always defaults to the HTTPS version of the registry. ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

Using Lambda functions as a module in node.js

I have come up with an idea to run the lambda function below as a node module. Node.js Server: var express = require('express'); var app = express(); var server = require('http').Server(app); server.listen(2006, function () { co ...

Modify the starting URL in a Node.js application to /foo instead of just /

I am looking to visit a website with a default index URL like localhost:XXXX/foo, instead of the usual localhost:XXXX/. How can I achieve this specific setup? Any suggestions on how to make this happen? ...

Is there a way to configure the text box to allow for range values input?

Is there a way to create an input box that only accepts values between 20 and 40? I want to restrict single numbers within that range. How can I define the range for this specific input box? If anyone can help me achieve this, it would be greatly apprecia ...

Asynchronous behavior in Node.js and MongoDB when using await for patch requests

After encountering an issue with syncing returns while using await, it became apparent that the problem lies within the response handling. While all the information successfully updates in MongoDB, the endpoint res.status(200).send(updatedData); ends up re ...

Automatically logging out users when their session expires

Currently, I am working on a nodejs(express) server along with a react front end that utilizes various APIs. The server token stores both a token and secret, and the secret is refreshed whenever the user logs out of the front end. This has caused an issue ...

Running several Angular requests simultaneously can trigger failures in test cases

I am facing an issue with my Angular 1.5 application and Rails 4.0 backend. During testing, when a Staff member logs in, three queries are simultaneously sent to the backend causing errors. Strangely, this issue does not occur in the development environmen ...

An error message indicating that the page is currently being unloaded has appeared

While working on a NodeJS-ReactJS Isomorphic App, I encountered an issue when clicking on a Link. An error message popped up saying: Uncaught (in promise) Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by ...