Unable to change the filename when utilizing Angular.js ng-file-upload

After uploading a file using Angular.js ng-file-upload, I am attempting to rename the file. However, when I remove the properties

ngf-min-height="400" ngf-resize="{width: 400, height:400}"
, I encounter an issue. Below is my code:

<input type="file" data-size="lg" name="bannerimage" id="imagefile1" ng-model="file" ngf-pattern="image/*" accept="image/*" ngf-max-size="2MB" ngf-min-height="400" ngf-resize="{width: 400, height:400}" custom-on-change="uploadFile" ngf-select="onFileSelect($file);" >

The corresponding controller code is as follows:

$scope.onFileSelect = function($files) {
         fileURL=$files;
         $scope.imageData='';
    }
var file=fileURL;
var today=(Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
var newpath=today+"_"+ file.name;
file.name=newpath;

In the above code, I am appending a random number to the file name and replacing it successfully. However, if I remove

ngf-min-height="400" ngf-resize="{width: 400, height:400}"
from the file input like so:

<input type="file" data-size="lg" name="bannerimage" id="imagefile1" ng-model="file" ngf-pattern="image/*" accept="image/*" ngf-max-size="2MB" custom-on-change="uploadFile" ngf-select="onFileSelect($file);" >

In this scenario, I am unable to replace the file name and do not require restrictions on the file's height and width.

Answer №1

The ng-file-upload Upload Service provides a solution for this issue. Check out the following example:

$scope.$watch('selectedFile', function () {
    uploadSelectedFile($scope.selectedFile);
});

function uploadSelectedFile(file) {
  if (!file) {
    return;
  }

  file = Upload.rename(file, "newName.ext");

  Upload.upload({
        url: <api endpoint for file upload>,
        data: {file: file}
    }).then(function (resp) {
      //success
    }, function (resp) {
        //error handling
    }, function (evt) {
       //show progress
    });
}

Answer №2

give this code a try

<input type="file"  data-size="lg" name="bannerimage" id="imagefile1"  ng-model="file" accept="image/*" ng-file-select="onFileSelect($files[0]);" >

$scope.onFileSelect =function(file){
    filename = 'octavia.' + file.name.split(".")[1];
    var imgFile = new File([file], filename, {type:file.type});
    console.log(imgFile);
};

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

"Unexpected behavior: NextAuth is failing to return defined custom scopes

I am currently working on a NextJS project that utilizes NextAuth. Initially, everything was functioning properly with the default scopes. However, my project now requires additional claims, which are listed in the supported scopes here. "scopes_supporte ...

The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow: UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.n ...

jQuery when - anticipate the fulfillment of multiple success/done callbacks

When using $.when to determine when an array of ajax promises are finished, I have noticed that although the ajax calls themselves are completed when $.when fires, their callbacks and done functions are not. How can I make sure to wait for the callbacks to ...

Trigger an alert message upon loading the HTML page with search text

I need to search for specific text on a webpage and receive an alert if the text is found. <script type='text/javascript'> window.onload = function() { if ((document.documentElement.textContent || document.documentElement.innerText ...

Display information in a div container from other pages on the website

I am attempting to dynamically load content into a div in Index based on the selection made in a dropdown box, but it doesn't seem to be working correctly. I have created a simple example using four pages to demonstrate the issue: Index.html one.html ...

Is there a way to nest arrays within arrays in JavaScript?

Array ( [0] => Array ( [contactId] => 5 [companyId] => 54 [personName] => Awais [contactNo] => 0321-1111111 [contactType] => Partner ) ) data[0].personName I ...

The jquery error NS_ERROR_XPC_BAD_CONVERT_JS is causing issues on Google Chrome while working fine on Firefox

Currently, I am utilizing jQuery to dynamically add fields to a form. These are considered "repeatable" fields since users can click an "add more" button. Here is the code snippet: $(".add-attacker-scores").click(function() { count = count + 1; ...

Tips for transferring information from one php page to another php page via ajax

I am attempting to retrieve data from one PHP page and transfer it to another page through the use of Ajax. JavaScript : $.ajax({ url: "action.php", success: function(data){ $.ajax({ url: "data.php?id=data" ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

Incorporate a distinct identifier for every menu item within the Material UI TablePagination

Can a unique identifier be assigned to each menu item generated using the <TablePagination> component? I would like to add a specific ID (e.g., id="menu_item_0", id="menu_item_1" & id="menu_item_2") to the menu item ...

Transitioning from JSTL's forEach loop to angular.js's ng-repeat functionality during the spring season is like switching your

I am just getting started with angular.js. I currently have a spring MVC application and I want to transition from jstl to angular.js. This is how I began the process: <table> <c:forEach var="list" items="${list}"> <tr c ...

Valid method of confirming a user's login status

Using AJAX requests, I have implemented a user area on my website. The "Log off" button is supposed to be displayed only when the user is logged in. Here is the AJAX request for logging in a user: function requestSI() { var xhr = getXMLHttpRequest(); xhr ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Are Opera and IE9 blocking cross-origin Ajax requests?

I have been utilizing the following page - - to initiate a cross-origin Ajax request towards this specific resource: The functionality appears to be functioning as expected in Chrome, Safari, and Firefox, but encounters an issue in IE9 and Opera. Below ...

Struggling to start the node express server running

I'm trying to set up a node server using express to run nodemailer. My frontend is built with create-react-app - I believe there should be no issues in that area. I have a few questions: Why isn't my express server functioning properly? Why do I ...

Node.js Express not inserting data with Mongoose when using form data

For the past two weeks, I have been struggling to post data to insert into a database using form-data. It consistently shows a 400 bad request error. Below is my code for server.js: require('./db.js') let express = require('express') ...

Utilize the https://angular-translate.github.io/ website for translating text

I have been utilizing the module to handle translations. The array of keys I am using is: $scope.array = [ "full_name", "email", "phone_no" ]; For translation, my key-value pairs are set as follows: $translateProvider.translations('en ...

Tips for providing arguments in the command line to execute a yarn script

Just starting out with JavaScript. I understand that npm allows for passing variables in the command line using process.env.npm_config_key like this: npm run --key="My Secret Passphrase" test:integration How can I achieve the same thing with yarn? I&apo ...

Using Google's Closure Compiler to Optimize JSON Files

When dealing with a json string that is parsed and properties of the object are accessed using dot notation, a warning may be triggered by the google closure compiler stating that the property is not defined. To overcome this issue, one workaround is to c ...

Vue.js causing issues with jQuery data table

Utilizing jQuery data-table within Vue.js in a laravel project has presented an issue for me. Although the data loads successfully into the data-table, there seems to be a problem with retrieving the data after it has been loaded. Specifically, the first r ...