Using Angular's $http service to send a file to a web API endpoint from a post function

I'm facing an issue with uploading a javascript file or transmitting a javascript file to a post function. On the client side, I am using angularjs $http service to send the data as follows:

$http({    
                    method: "POST",
                    url: "/api/fileupload",
                    data: JSON.stringify(scope.c.model), // where scope.c.model is the javascript File
                    contentType: "application/json"

                }).then(successResponse => {
                    this.scope["text"] = "Success...";
                }, errorResponse=> {
                    this.scope["text"] = "Error...";
                });

Here is the web-api controller:

    public void Post(HttpPostedFile file)
{
    //do stuff...  
}

The issue is that 'file' is null while scope.c.model contains the correct data. When I change the type of data to an array, it works fine. It seems like the post method is not recognizing the file.

The second approach below also does not work, as file.Count returns zero.

public void Post() 
    {
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {
             //do stuff...
        }
    }

Answer №1

Below is the solution to the problem. With the code provided, I am able to save any file either locally or on the server.

Client Side

scope.c.model represents the Javascript FILE API. The model in the background is defined as ng-model = model. Here, c refers to the controller. Since this code is within the link function of my directive, I can access the model through scope.c.model. The name of the model can be anything. To read the File, I need to use FileReader.

            scope.$watch('c.model', () => {
            if (scope.c.model != null) {

                var reader = new FileReader();
                reader.onload = () => {
                    var base64 = reader.result.split("base64,")[1];
                    var file = {
                        content: base64,
                        name: scope.c.model.name,
                        type: scope.c.model.type,
                        size: scope.c.model.size
                    };
                    var t = file.content;
                    $http({
                        method: "POST",
                        url: "/api/fileupload", //web-api controller
                        data: file, // scope.c.model is the JavaScript File
                        contentType: "application/octet-stream"

                    }).then(successResponse => {
                        this.scope["text"] = "Success...";
                    }, errorResponse=> {
                        this.scope["text"] = "Error...";
                    });
                };
                reader.readAsDataURL(scope.c.model);             
            }
        });


Server Side

public class File
{
    public string Content;
    public string Name;
    public string Type;
    public string Size;
}
public class FileUploadController : ApiController
{
    public void Post(File file)
    {
        var bytes = Convert.FromBase64String(file.Content);
        using (var imageFile = new FileStream(@"C:\fileupload\"+file.Name + ".jpg", FileMode.Create))
        {
            imageFile.Write(bytes, 0, bytes.Length);
            imageFile.Flush();
        }
    }
}

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

jQuery script unable to alter img src in Firefox and IE browsers

I am working with an image and a jQuery script to change the captcha image. <img src="captcha.jpg" id="my-image"/> The jQuery script is as follows: <script> $(document).ready($("#my-image").click(function(){ $('#my-image&ap ...

Default parameters for the ngMessages directive

I am looking for a way to make modifications to AngularJS Material inputs without having to create a new directive or add attributes everywhere. Is there a way to parameterize all ngMessages directives without the need to add them individually? <md-inp ...

JavaScript opacity adjustments not achieving desired outcome

My attempt to make this sub menu fade in and out upon button press is not working as expected. It should fully fade in shortly after clicking 'help' and completely fade out when clicking 'back'. Is the problem with the method I'm u ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Struggling to make fadeIn() function properly in conjunction with addClass

I've been struggling with this issue for quite some time now and I just can't seem to make it work. The JavaScript I'm working on involves using addClass and removeClass to display and hide a submenu element. While the addclass and removeCla ...

Display a loading screen with a progress bar using React Native Expo

Currently, I am diving into the world of React Native and honing my skills using Expo. One of the tasks I've tackled is creating a loading screen for my app using npm react-native-progress. However, I'm curious if there is a way to replace the de ...

How can I combine columns within a single header in ng-table?

Looking to create a table layout with headers 'a+b' above, followed by separate headers for 'a' and 'b'. Here is the desired structure: +-------------+---------------+ | headerAB | HdrC | +-------------+ ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

Uncaught TypeError occurs in AngularJS and Mocha testing when the function (window.beforeEach || window.setup) is not defined

I've been experimenting with testing angular js using mocha in my meteor application. After installing ngMock and injecting it into my module, I encountered an issue right when starting my app. Regardless of whether I installed ngMock from atmosphere ...

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the t ...

Strategies for managing Shopify's API request restrictions with the microapps Node.js module

I've been struggling to find a solution to this problem and I just can't seem to get it right. I'm currently using a Node.js module for the Shopify API created by microapps. In my JSON object, I have a list of product IDs and SKUs that need ...

Collapse the mobile nav bar upon clicking an item

I'm currently facing a challenge with the navigation bar on my event landing page. The issue is that when I open the navbar in mobile view, it does not collapse back after clicking on an item. Instead, it remains open and covers almost 3/4 of the scre ...

The problem with Vue JS static links

I'm currently working with a Vue.js application (v2). I've noticed that if I skip visiting the root of the site, the sub-links do not work properly. For example: Visit: Then go to If I directly visit: I encounter the following error messag ...

A directive in Angular that leverages the same model but presents varying data

I'm currently developing a custom directive for pagination to be used in two different places on my page. The goal is to have the same pagination directive for two tables of data. Below is the code snippet for the directive: app.directive('pagin ...

Troubleshooting a Node.js server issue with a two-dimensional array

I am currently facing an issue with submitting a form that contains two-dimensional array fields on a post request in node.js. The problem lies in the fact that the server side is receiving a one-dimensional array with all the values combined. Below is an ...

How can I connect a jQuery slider to dynamically update a div's content?

I am trying to update the content of a Message div based on the position of my slider. Since my slider only has 5 positions, I need to display 5 different messages depending on which position is selected. Does anyone know how to accomplish this? Here is t ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...