Optimal method for transferring a file along with supplementary parameters from an Angular client and effectively managing them on the server

I have a method in my service that requires three parameters to be sent to the server.

setMainPhotoFor: function(file, petName, petId) {
            ...
}

Here is my current approach:

Client side

services.js

setMainPhotoFor: function(file, pet) {
            var baseServerApiUrl = configuration.ServerApi;
            var data = new FormData();

            data.append("image", file);
            data.append("petName", pet.Name);
            data.append("petId", pet.ID);

            $http.post(baseServerApiUrl + '/pictures/main-picture/add', data, {
                headers: { "Content-Type": undefined }
            });
        }

Server side

PicturesApiController

[HttpPost]
[Route("main-picture/add")]
public async Task<HttpResponseMessage> SetMainPicture()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    var provider = new MultipartMemoryStreamProvider();

    await Request.Content.ReadAsMultipartAsync(provider);

    MemoryStream mainPicture = new MemoryStream(await provider.Contents[0].ReadAsByteArrayAsync());
    string petName = await provider.Contents[1].ReadAsStringAsync();
    int petId;

    if (!int.TryParse(await provider.Contents[2].ReadAsStringAsync(), out petId))
    {
        //...
    }
    //...

However, I feel that there could be a more elegant solution for this task. Can anyone suggest a better approach?

Answer №1

If you want to send a multipart form using Angular, make sure to include the following options:

$http.post(baseServerApiUrl + '/pictures/main-picture/add', data, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        });

Answer №2

I previously provided a solution to this issue here using server-side sample code.

The recommended approach is to stream the content and include your dto in a header. After experimenting with several methods, I believe this is the most effective way to handle it.

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

An introduction to the basics of AngularJS, AJAX, and ASP.NET MVC

I am struggling with creating a simple AngularJS example that makes an AJAX call to an ASP.NET MVC action method. I have tried various approaches but haven't been successful yet. Below is the code snippet I have been working on... The ASP.NET MVC act ...

Attaching the `data-ng-click` event binding to the Document Object Model

I am a beginner to angularjs and I am facing an issue with my code. When I click the 'button', a new row is inserted with a 'new button'. However, I want the 'new button' to also have an ng-click event. The problem is that eve ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

Redux-Persist does not save the state in the browser's local storage

My goal is to store specific reducer state in localStorage so that it remains even after a browser refresh. However, when I check the storage, all I see is: "persist:root", "{"_persist":{\"version\":-1,\&qu ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Display the picture for a few moments, then conceal it. A button will appear to reveal the following image after a short period

For my project, I want to create a webpage for school where I display one image that disappears after 5 seconds, followed by a button. The user must click the button before the next image appears and stays for another 5 seconds. This sequence repeats each ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet: ngOnInit(): void { this.categories = this.categoryService.getCategories(); var example = this.categories.flatMap((categor) => categor.map((categories) = ...

Identify the failing test cases externally using JavaScript

I am currently tackling an issue where I am seeking to identify the specific test cases that fail when running a test suite for any javascript/node.js application. Finding a programmatic solution is crucial for this task. Mocha testsuite output result Fo ...

Using Selenium with Java to extract a value from an input text field that is disabled

I've encountered an issue while using Selenium in Java to retrieve a value from an input field. Here's the HTML snippet that I'm working with: <input class="form-control input-sm " id="NameInputID" type="text" maxlength="16" name="NameIn ...

What is the best way to store a global visible user in an Angular 2 application?

Upon logging in, I am able to retrieve the user. private login() { let data = { "UserName": "admin" , "Password": "+" }; this.apiService.doLogin(data).subscribe( (res) => this.userService.set('user', res), (err) => c ...

Removing a value from an array of objects in Angular 2

There is a single array that holds objects: one = [ {name: 'Name', key: '4868466'}, {name: 'Name', key: '4868466'}, {name: 'Name', key: '4868466'}, {name: 'Name', key: & ...

prevent $location.path from causing the page to reload

Despite researching this issue extensively on stackoverflow and google groups, I still can't seem to pinpoint why my app is not functioning correctly. The problem arises when I added reloadOnSearch: false, to the route, yet the page continues to r ...

Tips for effectively utilizing nodejs soap

Here's the code snippet I've been working on: soap.createClient(url, function(err, client) { if(err) { res.status(500); return res.send(err); } client.GetMemberPIN({pUserName: 'r'}, function(error, result) { if(erro ...

Analyzing the Threejs application for profiling purposes

Recently, I noticed that my webgl application developed using threejs is facing some performance issues in terms of FPS on certain machines. To diagnose the problem, I attempted profiling my application using Chrome's about:tracing feature, following ...

The functionality of vue-fullscreen does not seem to be operational when used within

I am currently utilizing the Vue-fullscreen library for my project. I have successfully implemented it on a video tag to enable full-screen functionality: <fullscreen ref="fullscreen"> <video :srcObject.prop="videosource" ...

The power of combining React with Three.js

My 3d image is failing to display on the screen. I'm utilizing React with Three.js and encountering the following error message: "THREE.Object3D.add: object not an instance of THREE.Object3D." Below is my component structure: (file tree provided). ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

What iteration of the ECMAScript specification does the CEF platform accommodate?

Could you assist me in identifying the compatible version of ECMAScript in the chromium embedded framework (cef)? I am interested in utilizing ECMAScript 6 with it. ...