Send a file from Angular to an ASP.NET controller

i am trying to upload a file using the following code in angular:

<input class="fromFileInput" id="VeryfyFromFileInput" type="file" fileread="fileContent" ng-click=uploadFile />

in my controller, I have the following code:

    $scope.fileInformation = [];

    $scope.uploadFile = function () {
        $scope.fileModel = $('#VeryfyFromFileInput');
        recordsService.passFile($scope.fileModel.context);
    };

and in my service, I have the following code:

        this.passFile = function (data) {
        return $http({
            method: 'POST',
            url: url + "/GetFile",
            data: data,
            headers: { 'Content-Type': 'application/json' }
        });
    };

I am trying to pass the file to an ASP.NET MVC controller using the following code:

    [HttpPost]
    public void GetFile([FromBody] HttpRequestMessage file)
    {

    }

However, I always end up with a null value. Can anyone advise me on what type of parameter I should use instead of 'HttpRequestMessage '? Or could the issue be on the javascript side?

Answer №1

Transmitting bytedata as application/json over the wire is not possible. One workaround is to utilize a Form Data object and execute the ajax call as multipart/formdata. Follow this Ajax call template:

         $.ajax({
                url: 'api/controller/action',
                processData: false,
                contentType: false,
                type: 'POST',
                data: formDataObject,
                success: function () {
                    alert('Success!');
                },
                error: function () {
                    alert('Error :c');
                }
            });

I made use of an angular-ui file upload directive. If your method of accessing it is effective, you can directly apply this syntax to include your file in FormData:

var formDataObject = new FormData();
formDataObject.append('file', $scope.fileModel;

Retrieve your data on the server using this code snippet:

 var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();
 foreach (var stream in filesReadToProvider.Contents)
 switch (stream.Headers.ContentDisposition.Name)
                {
                    case "\"file\"":
                        byte[] fileData = await stream.ReadAsByteArrayAsync();
                        break;
                    default:
                        break;

                }

            }

To learn how to save a byte array as a file on the server, refer to: Write File to server

Best of luck!

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

Incorporating Javascript jQuery functionalities from an external file

I have encountered an issue when trying to run my index.html file with the control.js file that I outsourced. It seems like they are not working together properly: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.c ...

What steps should I take to resolve the issue with running npm start?

I am encountering an issue while using React and trying to run my application. When I execute "npm run start," I receive the following error message: npm ERR! Missing script: "start" npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark ...

The event handler for clicking on the inner <li> element is not being triggered

I am encountering an issue in my React project, The problem lies within a menu structure that contains nested sub-menus. Here is the snippet of code: <ul id="main-menu-navigation" data-menu="menu-navigation" ...

Is it feasible to update the value of a FormArray within a FormGroup?

Hey there, I'm new to working with reactive forms and I have a question about updating a FormArray without using the get method. Typically, I would use something like this.editForm.get('ingredients'). However, I would like to use patchValue ...

Understanding how to accurately pair specific data points with their corresponding time intervals on a chart

I'm currently working with apexcharts and facing an issue with timestamps. I have data for sender and receiver, each having their own timestamps. The x-axis of the graph is based on these timestamps, but I am struggling to map the timestamp with its r ...

Delete the radio button list within the content placeholder

I'm having trouble with accessing elements by name on a master page content placeholder. Can someone assist me with this issue? Thank you in advance. <asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <script type="tex ...

How to cover the entire screen with a modal window?

<a href="#dialog" name="modal">Simple Modal Window</a> <div id="boxes"> this content should appear below the modal <!-- #customize your modal window here --> <div id="dialog" class="window"> <b>Tes ...

What benefits does NewRelic offer?

We are looking for a way to monitor events within our application and send the data to a monitoring server such as NewRelic. Our goal is to set up alerts based on this custom data. For instance, we would like to receive an alert if an event does not occur ...

What could be causing the discrepancy in the model value when using checkboxes in AngularJS?

Something strange is happening with my code. I have a checkbox in my view that has a directive to display its value when it changes. Surprisingly, it works fine in Firefox, showing the correct values. However, in other browsers like Chrome, it shows the op ...

What is the process of installing an npm module from a local directory?

I recently downloaded a package from Github at the following link: list.fuzzysearch.js. After unzipping it to a folder, I proceeded to install it in my project directory using the command: npm install Path/to/LocalFolder/list.fuzzysearch.js-master -S Howe ...

Working with checkboxes generated through v-for loop manipulation

Greetings everyone, this is my first time reaching out for help, so please bear with me. I am encountering difficulties with vue-js specifically related to component manipulation. My issue lies in creating checkboxes from an array that consists of a Strin ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

Discovering the art of importing JavaScript files dynamically within controllers

I have one main form through which I pass data from 10 different components, each including the ID of a table that I need to retrieve data from in the database. The issue I am facing is that the code responsible for fetching this data asynchronously is spr ...

Changing dates in controller using AngularJS

Does anyone have suggestions on how to convert a date from the format 1387843200000 into 24/12/2013 within my controller? Just to let you know, my dates are stored in this manner and when binding to an edit form with an input type="date field, it is not b ...

Exploring jQuery's Ability to Manipulate Data

I am encountering an issue with this particular piece of code: function MyClass() { var me = this; var $divElement = $('<div/>'); $divElement.data('object', me); this.retrieveElement = function() { return ...

Why is the renderer using viewport and scissor in Three.js resulting in a fully black canvas?

My user interface setup consists of two vertical windows - the left for the canvas and renderer, and the right for the UI components. Within this UI layout, I plan to include special viewers like a top view window. I have implemented the viewports and sc ...

Switch to a different element by rolling over one

I need assistance with a menu setup where the submenus are located in separate divs on the page. Both the parent elements and submenus have numerical identifying IDs, and I am struggling to create a rollover effect that would automatically open the corresp ...

Using the PATCH method in Rails instead of POST

i have some code to display here <%= form_for @campaign, url: brands_campaign_path(@campaign), method: :patch, :html => {:multipart => true, :class => 'form-horizontal'} do |f| %> and it generates the following <form class ...

Struggling with parsing a JSON file in C# and looking for some guidance

I have encountered an issue while working with a JSON file in C#. { "Company": { "ABC": {"ADDRESS" : "123 STREET", "DEF" :"ADDRESS 567", }, }, "Country": { "Country1": "XYZ", ...

Should websites developed in PHP, Rails, Django, or ASP have been coded in C++ instead?

Recently, I stumbled upon a member of the StackOverflow community's open source project. It caught my attention because it was a web framework developed in C++. I know what you're thinking - C++ isn't an ideal language for web development a ...