Problem with the ng-file-upload function failing to activate another function

I am attempting to upload a file to my server by saving a path to the database and the file to a folder. I have tried using ng-file-upload, and here is my code:

<form ng-show="divPatient" name="PatientForm" ng-submit="AddUpdatePatient()">
  <table>
    <tr>
      <td>
        <input class="form-control" type="text" readonly placeholder="Key (Automatic)" ng-model="PatientID" />
      </td>
      <td>
        <input id="FormFocus" name="FirstName" class="form-control" type="text" placeholder="FirstName" ng-model="FirstName" ng-minlength="3" required />
      </td>
      <td>
        <input name="LastName" class="form-control" type="text" placeholder="LastName" ng-model="LastName" ng-minlength="3" required />
      </td>
      <td>
        <input class="form-control" type="text" placeholder="Disease" ng-model="Disease" name="Disease" ng-minlength="3" required />
      </td>
      <td>
        <input class="form-control" type="number" placeholder="Phone No." ng-model="PhoneNo" name="PhoneNo" ng-pattern="/^[789]\d{9}$/" required />
      </td>
      <td>
        <input type="file" ng-file-select="onFileSelect($files)" class="form-control" ng-model="PhotoURL" required />
      </td>
      <td colspan="2">
        <input type="submit" value="save" class="btn btn-success" ng-disabled="PatientForm.PhoneNo.$dirty && PatientForm.PhoneNo.$invalid || PatientForm.LastName.$dirty && PatientForm.LastName.$invalid || PatientForm.FirstName.$dirty && PatientForm.FirstName.$invalid || PatientForm.Disease.$dirty && PatientForm.Disease.$invalid" />
        <input type="button" value="cancel" class="btn btn-primary" ng-click="CancelForm()" />
       </td>
       </tr>
       <tr>
        <td></td>
       <td><span class="eror-text" ng-show="PatientForm.FirstName.$error.minlength">min 3 letters</span></td>
       <td><span class="eror-text" ng-show="PatientForm.LastName.$error.minlength">min 3 letters</span></td>
       <td><span class="eror-text" ng-show="PatientForm.Disease.$error.minlength">min 3 letters</span></td>
       <td><span class="eror-text" ng-show="PatientForm.PhoneNo.$error.pattern">Invalid phone no</span></td>
     </tr>
   </table>
 </form>

Here is my Angular code:

var app = angular.module('StudentApp', ['ngFileUpload']);
app.controller("StudentCtrl", function ($scope, angularService) {

    $scope.selectedFile = [];

    $scope.onFileSelect = function ($files) {
        alert("where am I ???");
    }

$scope.AddUpdatePatient = function () {
    var file = $scope.selectedFile[0];
    alert($scope.PhotoURL);
    var Patient = {
        FirstName: $scope.FirstName,
        LastName: $scope.LastName,
        Disease: $scope.Disease,
        PhoneNo: $scope.PhoneNo
    };
    var getAction = $scope.Action;

    if (getAction == "Update") {
        Patient.PatientID = $scope.PatientID;
        var getData = angularService.UpdatePatient(Patient,file);
        getData.then(function (msg) {
            GetAllPatients();
            alert(msg.data);
            $scope.divPatient = false;
        }, function () {
            alert('Error in updating record');
        });
    } else {
        var getData = angularService.AddPatient(Patient);
        getData.then(function (msg) {
            GetAllPatients();
            alert(msg.data);
            $scope.divPatient = false;
        }, function () {
            alert('Error in adding record');
        });
    }
}

My dependencies:

bundles.Add(new ScriptBundle("~/bundles/CustomPlugins").Include(
                  "~/Scripts/ng-file-upload-shim.min.js",
                  "~/scripts/angular.min.js",
                  "~/Scripts/ng-file-upload.min.js"));

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/CustomPlugins")

I have tried using onchange:

onchange="angular.element(this).scope().selectFileforUpload(this.files)"

But I am unable to send the file to my action result, as it is showing as null:

$scope.selectFileforUpload = function (files) {
    $scope.selectedFile = files;
}

$scope.AddUpdatePatient = function () {
    var file = $scope.selectedFile[0];
    var Patient = {
        FirstName: $scope.FirstName,
        LastName: $scope.LastName,
        Disease: $scope.Disease,
        PhoneNo: $scope.PhoneNo
    };
        var getData = angularService.AddPatient(Patient,filee);
        getData.then(function (msg) {
            GetAllPatients();
            alert(msg.data);
            $scope.divPatient = false;
        }, function () {
            alert('Error in adding record');
        });
}

Here is my service code:

this.AddPatient = function (patient, file) {
    alert("in services" + filee);
    var response = $http({
        method: "post",
        url: "AddPatient",
        data: JSON.stringify(patient),
        dataType: "json",
        file : file
    });
    return response;
}

And finally, my action result:

public string AddPatient(Patient patient,HttpPostedFileBase file)
    {
         // I'm getting patient data that is fine, but file is showing me null
    }

Is there anything wrong with my service method? Or do you know how to send a form along with files to the action result in MVC controller? I have heard some people use "new FormData", but I am willing to learn or use it if it solves my problem.

Answer №1

As mentioned by Guinn in the comments above, the 'ng' used in ng-file-upload is different from the one in your code.

Your experience aligns with what I have encountered when the incorrect directive is utilized.

Check out the ng-file-upload GitHub repository for some demos that you can test in your browser and adopt the same syntax to ensure seamless implementation:

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

Click on the react item to view more information

I'm brand new to React and I'm exploring the swapi API for the first time. My goal is to retrieve a list of films (movie titles) and then, when a title is clicked on, display the opening crawl from the JSON object. So far, I've been able to ...

Passing a jQuery dialog variable for use in a php function using ajax

I am struggling to successfully pass variables from jQuery to a PHP function using AJAX. I have included the necessary HTML and script, but I'm confused as to whether the PHP file specified in the "url:" parameter should be external or can it be follo ...

Having problems with route navigation in Angular/Rails when using multiple layouts

Currently, I am in the process of building an AngularJS application that connects to a RoR backend. However, I have encountered an issue when working with multiple layouts. The application is designed to display one layout for unauthenticated users and swi ...

Struggling to include the VividCortex angular-recaptcha dependency in the AngularJS module due to an

Struggling to integrate Google reCaptcha v2 into my AngularJS app. I attempted to utilize VividCortex's angular-recaptcha, but incorporating the dependency into my app module proved challenging. The current code within my module looks something like ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

Leveraging the firebreath plugin to trigger a folder dialog, enabling asynchronous selection of folders to preserve the smooth execution of Java Script without any blocking

I need to ensure that only one folder selection dialog is open at any given time. Once the user picks a folder, an event will be triggered to notify the JavaScript of the selected folder. In order to open the dialog, I have integrated code from this gist ...

I am unsuccessful in transferring the "side-panel content" to the side panel located on the main menu page

I am facing an issue where I want to pass My left and right Panel to the main menu page (dashboard), but it is not working as expected. The problem arises because the first page that needs to be declared is the login page (/ root) in my case. If I pass it ...

Deleting a file in Express.js after it has been downloaded from the local file system

I'm working on an Express handler that is designed to download a file after detecting a valid file path in the directory entries. The handler includes a command-line option to delete the file after it has been successfully downloaded: res.downloa ...

What is the most efficient method for transforming JSON data into an object using JavaScript?

Currently, my method in JavaScript involves utilizing the eval function to transform JSON data retrieved from the server into an object. eval ("myObject="+data); I have received feedback that using eval is considered 'evil' and could potentiall ...

Ways to display jQuery values as HTML text

Trying to concatenate the HTML text with the values of item.certificate_name has been a challenge for me. I've experimented with various methods, but none of them seem to work. The specific line I'm referring to is where I wrote . I have alread ...

Transferring time between functions in Vue.js: A journey from one function to another

Struggling to pass the value from checkMp3SizeAndDuration method function to data() {return { time: '' } } Check out the code snippet below: data () { return { time: '' } }, methods: { checkMp3SizeAndDuration ...

Heroku Node.js - Cross-Origin Resource Sharing (CORS) is functioning correctly for all API requests except for when using the image upload

Our web application contains numerous APIs that retrieve data from a Node.js server deployed on Heroku. Most of the APIs function correctly, with the exception of one that allows users to upload images to the server. While this API worked flawlessly in o ...

Creating interactive JavaScript elements that can be moved around within a container

I recently faced a challenge while attempting to make draggable elements within a div. The issue arose when I realized that I couldn't figure out how to drag each element individually without affecting the others. My current code only allows for handl ...

Ways to stop React from refreshing the page upon clicking the submit button

Is it possible to prevent a React component from reloading the page when a submit button is pressed? Here is an example of component code: class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignStat ...

Learn the step-by-step process of graphing equations in React similar to Desmos

I am currently attempting to create a graph of an equation based on user input, similar to how it is done on Desmos () For example While I have come across a function plotting tool at , I have encountered difficulties when trying to plot equations contai ...

What is the process for transferring selections between two select elements in aurelia?

I am attempting to transfer certain choices from select1 to select2 when a button is clicked. Below is my HTML code: <p> <select id="select1" size="10" style="width: 25%" multiple> <option value="purple">Purple</option> &l ...

Encountered a problem while trying to install using npm install

Encountering an error while running npm install on Ubuntu 12.04: Here is a snippet from my npm-debug.log showing where the errors occur: ... (contents of npm-debug.log) ... This is my package.json: { "name": "www", "version": "0.0.1", /"p ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

"GM_openInTab in Userscript (Scriptish) not working properly, returning null value

There seems to be a problem with window.opener that I am facing. When I utilize window.open("url"), the child window will reference window.opener properly. However, if I use GM_openInTab instead, which is supposed to be the equivalent option for cross bro ...