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

Utilize PHP in an APP Engine Application to send an email to a Gmail address

I have a project deployed on Google App Engine where I need to send an email once a user submits the contact form. My app is successfully deployed and I have implemented an ajax request to a PHP file, but unfortunately, it's not functioning as expect ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

When you press the back button and navigate to a different page, the scroll position will remain unchanged

I'm facing an issue with scrolling on my angularjs app. Currently, the app consists of 2 pages: The first page displays a list of customers, where you can select one to view their details. The second page is a list of companies, following a similar s ...

Struggling to successfully pass a function as an argument to the setTimeout method within an array in node.js using TypeScript

Here is an example that successfully demonstrates a function being called using setTimeout: function displayMessage(msg: string){ console.log(msg); } setTimeout(displayMessage, 1000, ["Hi!"]; After one second, it will print out "Hi!" to the console. ...

Error: An unexpected identifier was encountered while executing my function

I've been trying to implement a function that I found online, but when I try to run it in the terminal, I keep getting this error: /home/simone/gekko/strategies/high.js:10 sma: function(name, price, points) ^^^ SyntaxError: Unexpected identifier I ...

Conceal the ion-tabs in an ionic framework

I have been implementing a solution to hide ion-tabs by following this codepen example: <ion-tabs ng-class="{'tabs-item-hide': hideTabs}"> // --> my tabs content </ion-tabs> <ion-view hide-tabs> // --> my content ...

comparison of declarative loop and imperative loop

In my journey to transition from an imperative programming style to a declarative one, I've encountered a challenge related to performance when dealing with loops. Specifically, I have a set of original DATA that I need to manipulate in order to achie ...

Discover the ways in which an AngularJS function is able to generate HTML code containing an AngularJS

There is an issue here helper.getDataForTriggeredUploadOfMFFile = function (isTriggeredUploadMF) { if (!isTriggeredUploadMF) { return 'None'; } else { return '<spa ng-click=\"previewDataOnSmartAnalytics()>Preview Data</span&g ...

How can I make the top two divs stay fixed as I scroll down, and then reset back to their initial position when scrolled

Hey there, I'm looking to have a div stay fixed after scrolling within its parent div. <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div class="fw ofndr-box"> <div class="ofndr-box-half add-here"> <a href="#! ...

When using React, draggable components with input fields may lose their ability to receive focus when clicking on the input field

<Draggable axis="y" grid={[135,135]} onStop={this.handleStop} defaultPosition={{x: this.props.task.positionX, y: this.props.task.positionY,}}> <div id="edit-task-component"> <form onSubmit={this.handleSubmit} id=" ...

Using a Button component as a TableCell in a material-ui Table

Hey there! I'm looking for some assistance in adding buttons as TableRowColumns in the material-ui Table. I'm working on implementing an approval system to approve or reject user requests, and I thought presenting them in a tabular format would b ...

Using JavaScript along with Ajax and JSON allows for sending complex data structures such as objects and

One of the features on my form allows users to input information about their clients. This versatile form enables users to add multiple phone numbers, email addresses, and physical addresses without any limitations. When adding a phone number or an email ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Utilizing key values to access an array and generate a list of items in React.js

This marks my initiation on Stack Overflow, and I extend an apology in advance for any lack of clarity in my explanation due to unfamiliarity with the platform. My current task involves creating a resume with a dynamic worklist feature on my website. The ...

Implementing a sleek show/hide transition using slideToggle in jQuery

Trying to implement show/hide content with slideToggle and it's functioning, but the animation effect on the table is not smooth. Attempted two different codes, but none provided the desired animation effect: $('.more').slideToggle(' ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

What is the method to increase a counter in the view component using Angular?

Suppose I need to implement a counter in a recursive script that tracks the number of times the script is executed. However, instead of seeing an output like this: 1 2 3 ... I'm encountering this: 1 1 1 ... Below is the basic code I am working wi ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...