Customizing file names in sails using req.file('file')

Currently, I am working on sails and have been able to successfully upload a file from the client to the server without using a form. I am utilizing fs.createReadStream('file') for this purpose. The file data is sent to the server and everything works fine when uploading a file, but I want to change the file name to a random one each time. Below is the code snippet:

var uploadFile = req.file('file');
uploadFile.upload({
     maxBytes: 250000000000,
     dirname: '../../assets/videos'
   }, function onUploadComplete(err, files) {
if (err) {
       return res.json({
         status: false,
         msg: 'uploading error'
       }); // False for err
     } else {
       return res.json({
         status: true,
         msg: 'success',
         data: files
       }); // True for success
     }
   });

The 'files' variable holds a valid array, but it seems to change the file name automatically. I am wondering if there is an option available to set a custom name while uploading? For example:

var object = {
     maxBytes: 250000000000,
     dirname: '../../assets/videos',
     fileName: 'xyz.mp4'
   }

Any help or suggestions would be greatly appreciated :)

Answer №1

In order to save a file with a custom name, use the saveAs option when utilizing the default sails-skipper.

uploadFile.upload({
    dirname: 'path where you want to save the file',/* optional. defaults to assets/uploads by default*/
    saveAs: 'new desired file name', /* optional. defaults to original file name. Can also be set as a function */
    maxBytes: 5 * 1024 * 1024 //5 MB
},function onUploadComplete(err, uploadedFiles) {
    ...
})

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

Curious about how to utilize Gridfs to upload files or videos larger than 16mb with the help of express, mongoose, and mongodb?

I'm encountering an issue with my code. It works fine for uploading images, but when I try to upload videos or files larger than 16mb, it fails. I am a beginner and seeking help on what to do next. const Freecoursevideo = require("../models/freec ...

What is the method for conducting a partial data search in Node.js with MongoDB without explicitly specifying the field name?

After researching, I have found that the usual course of action is to specify field names. However, I am interested in achieving the same result without specifying any field name when saving JSON data into MongoDB and conducting partial searches. Is this ...

Node.js - Retrieving user information upon login in the front-end

I've successfully built a couple of expressjs applications in the past, but I'm currently struggling to figure out how to pass the User Model to the front-end or include it in the req as a parameter. The app functions as a one-page web applicati ...

What is the best way to encode and split audio files so that there are no gaps or audio pops between segments when I put them back together?

In my current project, I'm developing a web application that involves streaming and synchronization of multiple audio files. To accomplish this, I am utilizing the Web Audio API in conjunction with HTML5 audio tags to ensure precise timing of the audi ...

There was an issue executing GraphicsMagick/ImageMagick: the operation "identify" with the arguments "-ping" and "-format" "%wx%h" could not be completed

I am currently attempting to locate the measurements of the images on a production machine, but encountering errors. An error occurred while trying to execute GraphicsMagick/ImageMagick: identify "-ping" "-format" "%wx%h" "uploads/userPhoto-149966968519 ...

What could be causing my webpack (react) build to fail when these modules are missing?

Starting a new project, I faced the challenge of installing webpack. Despite trying to ignore unnecessary modules in package.json, I encountered 19 errors during the build process that were related to modules not installed or needed. After researching solu ...

Executing PHP within a Node environment on the Heroku platform

It may not be the best practice, but I find myself in a tricky situation. Currently, I have a project running on node on Heroku. Within this project, there is a lengthy and intricate php script that I am hesitant to rewrite. The thought of setting up anoth ...

The function res.send() is triggered before the nested function finishes executing and returns a value

I am currently facing an issue with the 'GetUsers' function. It seems that the function is returning the correct values, but when trying to send these values using res.send(users), it appears as undefined. I have attempted to move the res.send(us ...

"Unlocking the Potential of Passport-OAuth2 Client: Maximizing the Usage of Profile

I currently have a standalone oauth2 identity provider that is fully functioning. My next step involves developing a consumer that will authenticate users using this stand-alone provider. In order to achieve this, I am following this tutorial on passport ...

Error message encountered in node-schedule: Unable to read undefined property upon job restart

Using node-schedule, I have successfully scheduled jobs on my node server by pushing them into an array like this: jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url))); Everything is working as expected. When the designated date ...

Running promises in sequence with Node.js

Hey there, I'm looking for a way to run promises sequentially in Node.js. In the example below, I am looping through an array of hours and want to fetch results from the database for each hour in the same order as they were retrieved. angular.forEac ...

Tips for retaining form data after validation failure in a node.js application

Currently, I am working on validating form data using express validator. To keep the form fields populated even after a validation failure, I have split my routes and controllers into separate files. The validation process is being handled by express valid ...

What is the process for updating EJS template with AJAX integration?

Understanding the combination of EJS with AJAX has been a challenge for me. Most tutorials on AJAX involve using an API that responds with JSON objects. Below is an example of code: router.js router.get('/jobs', function(req, res) { Job.fi ...

Leveraging webpack for requiring modules in the browser

I've been attempting to utilize require('modules') in the browser with webpack for the past couple of days, but I could achieve the same functionality with browserify in just 5 minutes... Below is my custom webpack.config.js file: var webp ...

transforming yargs into process.argv

My instructor has requested that I exclusively use process.argv, so how can I convert the following code: const args = process.argv.slice(2); const command = args[0]; if (command === 'add') { const title = args[1]; const body = args[2]; ...

Loopback has a powerful access control feature that encompasses filtering capabilities

I have three models set up in Loopback: Reader, Book, and Note. The Reader model is essentially an instance of User and has the ability to log in. Here are the relationships between the models: Reader has many Books Reader has many Notes Book has many No ...

Tips for parsing BSON data using body parser in Express.js

I am currently working on a Node.js API utilizing Express.js with body parser to handle a BSON binary file sent from a python client. Below is the code snippet from the Python client: data = bson.BSON.encode({ "some_meta_data": 12, "binary_data": ...

Encountering a problem with the React version. Upgrading to a newer version

I've been facing issues with installing the latest version of react. Even after trying different methods like appending @ to specify a particular version or completely uninstalling nodejs, it still doesn't work. npm react --version 6.14.15 When ...

Utilizing MongoDB to create time-based event triggers

I am working on a front-end application using Angular and a back-end system powered by Express.js. My goal is to have notifications displayed on the front end based on meetings scheduled at specific times. For example: If there is a meeting scheduled f ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...