Tips for retrieving the text from a POST request in C#

I have a basic Angular form that allows users to upload a file along with a description.

constructor(private http: HttpClient) { }
upload(files) {
    if (files.length === 0)
      return;

    const formData: FormData = new FormData();

    var filedesc = this.description;

    for (let file of files) {
      formData.append(file.name, file);
      formData.append("Description", filedesc);
}
const uploadReq = new HttpRequest('POST', `api/upload`, formData, {
      reportProgress: true,
    });

When the file is uploaded, the controller only retrieves the file name.

[HttpPost, DisableRequestSizeLimit]
        public ActionResult UploadFile()
        {
            try
            {
                var fileContent = Request.Form.Files[0];

                string folderName = "Upload";
                var contenttype = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                string webRootPath = _hostingEnvironment.WebRootPath;
                string newPath = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                if (fileContent.Length > 0)
                {
                    if (fileContent.ContentType == contenttype)
                    {
                        string fileName = ContentDispositionHeaderValue.Parse(fileContent.ContentDisposition).FileName.Trim('"');
                        string fullPath = Path.Combine(newPath, fileName);

                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            fileContent.CopyTo(stream);
                        }

                    }
                    else
                    {
                        return Json("Wrong File Type.");
                    }

My question is how can I receive the description string in this scenario? Is it problematic to append the file and description in the same request?

Answer №1

As Aman B previously mentioned, incorporating a parameter and implementing the following code is recommended

 foreach (string key in Request.Form.Keys)
                {
                    description = key;
                }

Answer №2

To receive the description, make sure to add a parameter to your action method:

//For a single file description
public  ActionResult UploadFile(string description)
        {
  //Implementation..
}


    //For multiple file descriptions
    public  ActionResult UploadFile(IEnumerable<string> description)
            {
      //Implementation..
    }

You can send form data along with files in the same request by using the "multipart/form-data" content-type header.

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

View the HttpWebRequest as a string prior to calling GetResponse, without the need for fiddler

Is it possible to view the HttpWebRequest object as a string before calling the GetResponse method? I am looking to see the raw format of the request, similar to how it appears in Fiddler: Content-Type: multipart/form-data; boundary=---------------------- ...

Error encountered: Module 'redux-saga/effects' declaration file not found. The file '.../redux-saga-effects-npm-proxy.cjs.js' is implicitly typed as 'any'. Error code: TS7016

<path-to-project>/client/src/sagas/index.ts TypeScript error in <path-to-project>/client/src/sagas/index.ts(1,46): Could not find a declaration file for module 'redux-saga/effects'. '<path-to-project>/client/.yarn/cache/red ...

Issue: The system needs the 'image' property to proceed (Dall E's image variation API by OpenAI)

Utilizing the Dall E Create image variation API has been a bit challenging for me. Every time I send a post request, I encounter this particular error: error: { "code": null, "message": "'image' is a required property&q ...

Choose the default value of the select tag if hardcoded options are used with ngModel

When the value is set by using this.model.type = OPTION_NR1, Angular automatically sets the HTML attribute ng-reflect-model to 0. However, the desired value for this HTML attribute should be OPTION_NR1 in order to populate the drop-down with Option1 instea ...

Using TypeScript to Manipulate SVG Polyline Shapes

In my TypeScript 3.1.1 project in VS Code with an Aurelia setup, I am facing a challenge while trying to manipulate an SVG Polyline using TypeScript code. The issue arises when attempting to create a new SVGPoint object. The initial HTML structure is as fo ...

Error message in .NET MAUI: "An attempt was made to access an object that has already been disposed. Object reference not set to an instance of an object: 'Microsoft.Maui.Platform

During the development of my application using .NET MAUI, I have run into an issue that has me stumped. While debugging, I came across a peculiar exception when navigating pages on the Android platform. The app consists of two tabs: Homepage and Selfhelp. ...

The webpage is currently experiencing difficulty in displaying any information

As a beginner in React and typescript, I am working on a simple application that fetches data from an API and displays it on a web page. Despite fixing some errors and seeing the data in the console log, I am struggling to display any data on the actual we ...

Creating a fresh ngx-translate pipeline (comparing pure and impure methods)

Edit: I am looking to enhance the functionality of ngx-translate's pipe by extending it. Here is an example of how I achieved this: import { Pipe, PipeTransform } from '@angular/core'; import { TranslatePipe } from "@ngx-translate/core"; @ ...

What is the best way to simulate a service HTTP request using Jasmine in an Angular application?

Why is my spy not working as expected? I've set up a spy for the prescriptionService and am monitoring the fetchClientPrescriptions method, but when I try to verify if it has been called, I encounter an error. However, the spy for getClientPrescriptio ...

Encountering a 404 error when using the NestJS GET function within the service and controller

I am facing an issue with creating simple GET logic. When I test it in Postman, I keep receiving a 404 error. books.service.ts contains the following basic logic: constructor( @InjectRepository(Books) private readonly booksRepo: Repository<Boo ...

Seeking assistance with transforming a REST call from PHP to ASP.NET C#

I currently have PHP code that is utilized to make a REST call for sending SMS messages to phones. Here is the code snippet: if(isset($_POST['number'])){ $api_key = 'api_key'; $api_secret = 'api_secret'; $curl = curl_init(&ap ...

Having trouble retrieving my .scss bundle file from a different directory

I am trying to access my .scss file that imports all the other .scss files (they are all imported in styles.scss). Even though I have added the path to my angular cli file, the file is still not accessible and no styling is being applied to my html elemen ...

Clearing the require cache in Node.js using TypeScript

I need to repeatedly require a module in TypeScript and Node for testing purposes. I came across an approach on this post which suggests the following code snippet: const config = require('./foo'); delete require.cache[require.resolve('./fo ...

What is the best way to store a gridster-item in the database when it is resized or changed using a static function

Following some resize and drag actions on my dashboard, I aim to store the updated size and position of my altered widget in my MongoDB database. Even though the gridster library offers the ability to respond to draggable and resizable events, these events ...

Issue with Angular 6 and Html Webpack Plugin

My project was recently updated from Angular 5 to Angular 6, causing some changes in the file structure. The webpack.config files are no longer present and the project now operates under CLI engage. However, I encountered an issue after the migration rela ...

Invoke the HTTP API from the device application

I need to make an API call to a server that does not have the HTTPS protocol. I came across this post on Stack Overflow: https://stackoverflow.com/questions/57433362/api-calls-made-in-ionic-4-app-not-working-on-android-device The post mentions that HTTP ...

Leveraging the string.Split() method in AutoMapper during the conversion process

I have two classes called A and B. I am currently converting class A to class B. One of the properties in class A is a string that contains two date times within the same string value. class A { public string dates { get; set; } } class B: A { pu ...

Is it possible for a function within a nodejs module to be defined but display as undefined upon access?

I am currently developing a Discord bot using NodeJS and TypeScript, and I'm facing an issue while trying to import custom modules in a loop with the following code: const eventFiles = fs.readdirSync("./src/events/").filter((file: string) =& ...

Angular2: Learn how to dynamically create input fields when a button is clicked

My current challenge involves replicating input fields on click of a button. I have a set of input fields where data can be entered, and then I need to add another set of the same fields for additional data. There needs to be a way to remove these replicat ...

Discover the process of implementing nested service calls in Angular 2 by utilizing observables

Here are my component file and service file. I am trying to achieve that after the verification() service method is successfully called, I want to trigger another service method signup() within its success callback inside subscribe. However, I am encounter ...