Is there a way to upload a file and FormData simultaneously without storing the file on the server's disk?

When it comes to uploading files and FormData to a server, I found a method that works well:

On the client side, I am using Angular 2 with the following logic:

1. In the component

onLoadForeignLightCompanies(event: any) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
        let file: File = fileList[0];
        let formData: FormData = new FormData();

        formData.append('projectId', this.projectId);
        formData.append('file', file);
        this.companyService.uploadForeginLightCompany(formData).then(result => {});
        this.isLoading = false;
        window.location.reload();
    }
}

2. In the service

uploadForeginLightCompany(formData: FormData): Promise<any> {
    return this.http.post(this.baseUrl + 'foreignLightCompanyImport', formData).toPromise();
}

On the server side

public byte[] LoadUploadedFile(HttpPostedFile uploadedFile)
{
    var buf = new byte[uploadedFile.InputStream.Length];
    uploadedFile.InputStream.Read(buf, 0, (int)uploadedFile.InputStream.Length);
    return buf;
}

[HttpPost, Route("foreignLightCompanyImport")]
public async  void UploadForeignLigtCompanyCompanyFile()
{
    string root = HttpContext.Current.Server.MapPath("~/App_Data");

    var file = LoadUploadedFile(HttpContext.Current.Request.Files[0]);

    var provider = new MultipartFormDataStreamProvider(root);
    await Request.Content.ReadAsMultipartAsync(provider);

    var projectId = provider.FormData.GetValues("projectId")[0];

    ((IForeginLightCompanyService) Service).UploadDataFromExcel(file, Convert.ToInt32(projectId));
}

A common practice on the server side is to use

HttpContext.Current.Server.MapPath("~/App_Data");
However, this saves the files on disk. Is there a way to upload a file without saving it to disk while still being able to retrieve other parameters like projectId? Perhaps sending the file as binary string in JSON with other parameters from a model on the client side could be a solution. Does anyone have any insights or suggestions regarding this issue?

Answer №1

An elegant solution involves the use of a specific model:

public class UploadForeignCompanyNameCompanyFile
{
    public string ProjectId { get; set; }             
    public HttpPostedFileBase Attachment { get; set; }
}

You can then update your post action method to accept a parameter of this model type:

public async void UploadForeignCompanyNameCompanyFile(
    UploadForeignCompanyNameCompanyFile companyFile)
{
    // code...
}

Remember to adjust your view code so that it submits the necessary information to the action method.

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

The labels for my Angular Material form within the dialogue are not visible and the styling appears incorrect until I begin inputting information

https://i.sstatic.net/njp4A.png Upon opening the dialogue, I noticed that only the phone number, email, name, and location fields were properly styled, while the others were not and the labels weren't displaying. Prior to adding appearence="out ...

How come Bootstrap Select isn't displaying the selected value when I provide a default option?

Why is it that an object with a set value is only displayed initially if the "--Select--" parameter is omitted? Do you have any insights into this behavior? @Html.DropDownListFor(m => m.FlightDetails.AirlineId, ViewBag.AirlineList as SelectList, "--Se ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

The HTML canvas drawImage method overlays images when the source is modified

Trying to implement a scroll animation on my website, I came across a guide for creating an "Apple-like animation" using image sequences. Even though I'm new to Angular, I attempted to adapt the code to work with Angular. However, instead of animatin ...

Unable to execute the "install code command in PATH" command

I am encountering an issue with Visual Studio Code where the "install code command in path" option does not show up when I try to access it using Shift + Ctrl + P. My operating system is Windows 10 and I am running the latest version of Visual Studio Code. ...

Suggestions for implementing an Ajax file upload feature in ASP.NET MVC?

Looking for suggestions on a free Ajax file upload control for ASP.NET MVC. It should include a progress bar/percentage complete feature and be easy to use. Open source is preferred. I only want recommendations based on personal experience with the produc ...

"Encountering issues while setting up membership with MySQL in a new ASP.NET Razor project

After creating a simple project with a fresh MVC4 razor web page and a new empty MySQL database, I encountered the following exception: System.Reflection.TargetInvocationException was unhandled by user code Message=Exception has been thrown by the target ...

how can one exhibit the value of an object in TypeScript

Does anyone know how to properly display object values in forms using Angular? I can see the object and its values fine in the browser developer tools, but I'm having trouble populating the form with these values. In my *.ts file: console.log(this.pr ...

What is the reason for XMLHttpRequest.status being equal to 0 in all browsers except for Internet Explorer?

I am encountering a frustrating issue... After developing a standalone RESTful.NET webservice using C#, I noticed that when I make a XMLHttpRequest to fetch JSON data, all browsers, except for IE, fail to retrieve the data. The problem lies in the status ...

Applying multiple classes and conditions with Angular's NgClass directive

I am currently working on implementing a feature where the class name of a component within a div can be changed based on a button click. There are approximately five CSS classes that I would like to toggle on and off using ng-class. My main question is ...

What causes TypeScript to malfunction when using spread in components?

What is the reason for typescript breaking when props are sent to a component using a spread statement? Here's an example code snippet: type SomeComponentProps = Readonly<{ someTitle: string }> const SomeComponent = ({ someTitle }: SomeCompo ...

Determine the reference type being passed from a third-party component to a consumer-side component

I recently came across this issue with generics when using forwardRef in React: Property 'ref' does not exist on type 'IntrinsicAttributes' Let me explain my situation: import React from "react"; interface ThirdPartyComponen ...

Is it possible to convert JSON to enum using TypeScript?

I have a JSON string that looks like the following. { "type": "A", "desc": "AAA" } or { "type": "B", "desc" "BBB" } etc. How can I utilize an enum in Ty ...

Tips on navigating halfway down the row within a label control

I am currently using a label control, but the row it contains is too long and I want to move half of the line down. For example, the label looks like this: Follow American politics, keep up with the hottest political debates. I would like it to look l ...

What is the best approach to resolve CORS issue for an Angular application hosted on Heroku that is connected to a Postgres express backend?

I am currently in the process of deploying my Angular application along with a Postgres Express backend on Heroku to establish communication between them. However, I have encountered a major issue where whenever I attempt to utilize fetch methods, it promp ...

Retrieve an array containing objects with a subset of their properties. Typescript

Consider the array 'radicados' below: this.radicados = [{ id:0, asunto:'Facturas ADPRO Propias', consecutivo:'FAC-AB-00046', documentos: [{id:1, descripcion:'documento1.pdf', esAnexo:false, r ...

Developing a calendar UI with similar features and functionality to Google Calendar using Ionic 2

My journey with Ionic 2 began only one week ago and has been relatively smooth sailing thus far. However, I have hit a roadblock - I need to create a calendar interface for users to book time slots. Can anyone offer assistance on how to tackle this task? ...

Ways to verify whether a checkbox is selected and store the status in the LocalStorage

Hey there, I'm still new to the world of programming and currently just a junior developer. I have a list of checkboxes and I want to save any unchecked checkbox to my local storage when it's unselected. Below is a snippet of my code but I feel l ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

Utilizing Visual Studio Code for setting breakpoints in Typescript Jasmine tests

Currently, I am in the process of configuring a launch setup in Visual Studio Code for debugging my unit tests. The unit tests are written in Typescript, and both the tests and the corresponding code are compiled into a single js file with a source map. ...