.net core 2.2 & Angular 7: IFormFile in file upload controller is always nullFile Upload In Angular?.Net core controller does not work with dependency injectionFile upload using Asp.Net Core Web API file is always nullhow to uploading Iformfile with other model properties in asp.net core webapi?Angular Post json to .net core web api is nullWebAPI core IFormFile always showing nullIFormFile always return null in asp.net core 2.1Upload Image to PostgreSQL with .NET CoreUpload an Image with .NET Core 2.2Why file IFormFile = null?

How do I repair my stair bannister?

Global amount of publications over time

Is XSS in canonical link possible?

API Access HTML/Javascript

Why did the HMS Bounty go back to a time when whales are already rare?

Why do IPv6 unique local addresses have to have a /48 prefix?

Can a significant change in incentives void an employment contract?

Is possible to search in vim history?

Why is Arduino resetting while driving motors?

Greco-Roman egalitarianism

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

Find last 3 digits of this monster number

Did arcade monitors have same pixel aspect ratio as TV sets?

Will adding a BY-SA image to a blog post make the entire post BY-SA?

Why did the EU agree to delay the Brexit deadline?

Could the E-bike drivetrain wear down till needing replacement after 400 km?

Does the Mind Blank spell prevent the target from being frightened?

Diode in opposite direction?

MAXDOP Settings for SQL Server 2014

What is the gram­mat­i­cal term for “‑ed” words like these?

Did US corporations pay demonstrators in the German demonstrations against article 13?

Should I stop contributing to retirement accounts?

What does this horizontal bar at the first measure mean?

Can I use my Chinese passport to enter China after I acquired another citizenship?



.net core 2.2 & Angular 7: IFormFile in file upload controller is always null


File Upload In Angular?.Net core controller does not work with dependency injectionFile upload using Asp.Net Core Web API file is always nullhow to uploading Iformfile with other model properties in asp.net core webapi?Angular Post json to .net core web api is nullWebAPI core IFormFile always showing nullIFormFile always return null in asp.net core 2.1Upload Image to PostgreSQL with .NET CoreUpload an Image with .NET Core 2.2Why file IFormFile = null?













0















When looking at other answers and some google, everything seems to be fine, yet my controller never receives any data.



Api uris and such are correct, the request arrives at the correct controller



Angular snippet:



component.html - my input field



<div class="input-group">
<input type="file" #fileInput id="fileInput" (change)="stageFile()"
accept="csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
<div class="input-group-append">
<button class="btn btn-primary" type="button" (click)="fileUpload()" [disabled]="!staged || uploading">
<span *ngIf="!uploading,else loadAnim">Upload</span>
<ng-template #loadAnim>Uploading...</ng-template>
</button>
</div>
</div>


component.ts - get data from view



@ViewChild('fileInput') fileInput;
private file: File;
public uploading = false;
public staged = false;

constructor(private uploadService: UploadService)

public stageFile(): void
this.staged = true;
this.file = this.fileInput.nativeElement.files[0];
console.log(this.file)


public fileUpload():void
this.uploading = true;
if (this.file != null)
this.uploadService.upload(this.file).subscribe();
this.staged = false;
this.uploading = false;



services.ts - handle actual ajax call



private uploadURI = environment.dataServiceURI + '/upload';

constructor(private http: HttpClient)

public upload(file: File): Observable<object>
// create multipart form for file
let formData: FormData = new FormData();
formData.append('file', file, file.name);

const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data');

// POST
return this.http
.post(this.uploadURI, formData, headers: headers)
.pipe(map(response => response));



.net core snippet



It is here where IFormFile file always contains null and thus my result is always 500



[HttpPost("upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult ParseData([FromForm(Name = "file")] IFormFile file)

if (file == null)
return StatusCode(500);
(...)
return Ok()



Request Payload Info



From browser networking



------WebKitFormBoundarycBigaNKzS4qNcTBg 
Content-Disposition: form-data; name="file"; filename="test_data_schema.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

------WebKitFormBoundarycBigaNKzS4qNcTBg--









share|improve this question
























  • When you look at the network tab of your browser, does it send your file? Just to check if the problem comes from your frontend or your backend...

    – hugo
    Mar 5 at 22:19











  • yes it seems to send the file, at least the request payload contains a Content-Disposition and a Content-Type with the correct form-data values. Even if the payload would be empty I wouldn't know why. Any way to inspect if it actually sends a file and not just a filename? Logging the file to the console before sending it give me a size in bytes, but that's all I got.

    – pjominet
    Mar 6 at 8:58












  • There is a typo in your code: const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data'); --> "mulipart"

    – hugo
    Mar 6 at 18:06











  • I check against my dotnet code: public Task<IActionResult> Backup(IFormFile file) Maybe you should remove FromForm option because it's convention based ('file' in the payload will match 'file' in the parameters)

    – hugo
    Mar 6 at 18:07






  • 1





    Fund my error (thanks to @hugo) i took a closer look at my headers and there wasn't just a typo, but a mistake too. It has to be Content-Disposition not Content-Type

    – pjominet
    Mar 7 at 9:01















0















When looking at other answers and some google, everything seems to be fine, yet my controller never receives any data.



Api uris and such are correct, the request arrives at the correct controller



Angular snippet:



component.html - my input field



<div class="input-group">
<input type="file" #fileInput id="fileInput" (change)="stageFile()"
accept="csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
<div class="input-group-append">
<button class="btn btn-primary" type="button" (click)="fileUpload()" [disabled]="!staged || uploading">
<span *ngIf="!uploading,else loadAnim">Upload</span>
<ng-template #loadAnim>Uploading...</ng-template>
</button>
</div>
</div>


component.ts - get data from view



@ViewChild('fileInput') fileInput;
private file: File;
public uploading = false;
public staged = false;

constructor(private uploadService: UploadService)

public stageFile(): void
this.staged = true;
this.file = this.fileInput.nativeElement.files[0];
console.log(this.file)


public fileUpload():void
this.uploading = true;
if (this.file != null)
this.uploadService.upload(this.file).subscribe();
this.staged = false;
this.uploading = false;



services.ts - handle actual ajax call



private uploadURI = environment.dataServiceURI + '/upload';

constructor(private http: HttpClient)

public upload(file: File): Observable<object>
// create multipart form for file
let formData: FormData = new FormData();
formData.append('file', file, file.name);

const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data');

// POST
return this.http
.post(this.uploadURI, formData, headers: headers)
.pipe(map(response => response));



.net core snippet



It is here where IFormFile file always contains null and thus my result is always 500



[HttpPost("upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult ParseData([FromForm(Name = "file")] IFormFile file)

if (file == null)
return StatusCode(500);
(...)
return Ok()



Request Payload Info



From browser networking



------WebKitFormBoundarycBigaNKzS4qNcTBg 
Content-Disposition: form-data; name="file"; filename="test_data_schema.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

------WebKitFormBoundarycBigaNKzS4qNcTBg--









share|improve this question
























  • When you look at the network tab of your browser, does it send your file? Just to check if the problem comes from your frontend or your backend...

    – hugo
    Mar 5 at 22:19











  • yes it seems to send the file, at least the request payload contains a Content-Disposition and a Content-Type with the correct form-data values. Even if the payload would be empty I wouldn't know why. Any way to inspect if it actually sends a file and not just a filename? Logging the file to the console before sending it give me a size in bytes, but that's all I got.

    – pjominet
    Mar 6 at 8:58












  • There is a typo in your code: const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data'); --> "mulipart"

    – hugo
    Mar 6 at 18:06











  • I check against my dotnet code: public Task<IActionResult> Backup(IFormFile file) Maybe you should remove FromForm option because it's convention based ('file' in the payload will match 'file' in the parameters)

    – hugo
    Mar 6 at 18:07






  • 1





    Fund my error (thanks to @hugo) i took a closer look at my headers and there wasn't just a typo, but a mistake too. It has to be Content-Disposition not Content-Type

    – pjominet
    Mar 7 at 9:01













0












0








0








When looking at other answers and some google, everything seems to be fine, yet my controller never receives any data.



Api uris and such are correct, the request arrives at the correct controller



Angular snippet:



component.html - my input field



<div class="input-group">
<input type="file" #fileInput id="fileInput" (change)="stageFile()"
accept="csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
<div class="input-group-append">
<button class="btn btn-primary" type="button" (click)="fileUpload()" [disabled]="!staged || uploading">
<span *ngIf="!uploading,else loadAnim">Upload</span>
<ng-template #loadAnim>Uploading...</ng-template>
</button>
</div>
</div>


component.ts - get data from view



@ViewChild('fileInput') fileInput;
private file: File;
public uploading = false;
public staged = false;

constructor(private uploadService: UploadService)

public stageFile(): void
this.staged = true;
this.file = this.fileInput.nativeElement.files[0];
console.log(this.file)


public fileUpload():void
this.uploading = true;
if (this.file != null)
this.uploadService.upload(this.file).subscribe();
this.staged = false;
this.uploading = false;



services.ts - handle actual ajax call



private uploadURI = environment.dataServiceURI + '/upload';

constructor(private http: HttpClient)

public upload(file: File): Observable<object>
// create multipart form for file
let formData: FormData = new FormData();
formData.append('file', file, file.name);

const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data');

// POST
return this.http
.post(this.uploadURI, formData, headers: headers)
.pipe(map(response => response));



.net core snippet



It is here where IFormFile file always contains null and thus my result is always 500



[HttpPost("upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult ParseData([FromForm(Name = "file")] IFormFile file)

if (file == null)
return StatusCode(500);
(...)
return Ok()



Request Payload Info



From browser networking



------WebKitFormBoundarycBigaNKzS4qNcTBg 
Content-Disposition: form-data; name="file"; filename="test_data_schema.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

------WebKitFormBoundarycBigaNKzS4qNcTBg--









share|improve this question
















When looking at other answers and some google, everything seems to be fine, yet my controller never receives any data.



Api uris and such are correct, the request arrives at the correct controller



Angular snippet:



component.html - my input field



<div class="input-group">
<input type="file" #fileInput id="fileInput" (change)="stageFile()"
accept="csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
<div class="input-group-append">
<button class="btn btn-primary" type="button" (click)="fileUpload()" [disabled]="!staged || uploading">
<span *ngIf="!uploading,else loadAnim">Upload</span>
<ng-template #loadAnim>Uploading...</ng-template>
</button>
</div>
</div>


component.ts - get data from view



@ViewChild('fileInput') fileInput;
private file: File;
public uploading = false;
public staged = false;

constructor(private uploadService: UploadService)

public stageFile(): void
this.staged = true;
this.file = this.fileInput.nativeElement.files[0];
console.log(this.file)


public fileUpload():void
this.uploading = true;
if (this.file != null)
this.uploadService.upload(this.file).subscribe();
this.staged = false;
this.uploading = false;



services.ts - handle actual ajax call



private uploadURI = environment.dataServiceURI + '/upload';

constructor(private http: HttpClient)

public upload(file: File): Observable<object>
// create multipart form for file
let formData: FormData = new FormData();
formData.append('file', file, file.name);

const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data');

// POST
return this.http
.post(this.uploadURI, formData, headers: headers)
.pipe(map(response => response));



.net core snippet



It is here where IFormFile file always contains null and thus my result is always 500



[HttpPost("upload")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult ParseData([FromForm(Name = "file")] IFormFile file)

if (file == null)
return StatusCode(500);
(...)
return Ok()



Request Payload Info



From browser networking



------WebKitFormBoundarycBigaNKzS4qNcTBg 
Content-Disposition: form-data; name="file"; filename="test_data_schema.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

------WebKitFormBoundarycBigaNKzS4qNcTBg--






angular asp.net-core asp.net-core-webapi






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 6 at 9:07







pjominet

















asked Mar 5 at 17:32









pjominetpjominet

257




257












  • When you look at the network tab of your browser, does it send your file? Just to check if the problem comes from your frontend or your backend...

    – hugo
    Mar 5 at 22:19











  • yes it seems to send the file, at least the request payload contains a Content-Disposition and a Content-Type with the correct form-data values. Even if the payload would be empty I wouldn't know why. Any way to inspect if it actually sends a file and not just a filename? Logging the file to the console before sending it give me a size in bytes, but that's all I got.

    – pjominet
    Mar 6 at 8:58












  • There is a typo in your code: const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data'); --> "mulipart"

    – hugo
    Mar 6 at 18:06











  • I check against my dotnet code: public Task<IActionResult> Backup(IFormFile file) Maybe you should remove FromForm option because it's convention based ('file' in the payload will match 'file' in the parameters)

    – hugo
    Mar 6 at 18:07






  • 1





    Fund my error (thanks to @hugo) i took a closer look at my headers and there wasn't just a typo, but a mistake too. It has to be Content-Disposition not Content-Type

    – pjominet
    Mar 7 at 9:01

















  • When you look at the network tab of your browser, does it send your file? Just to check if the problem comes from your frontend or your backend...

    – hugo
    Mar 5 at 22:19











  • yes it seems to send the file, at least the request payload contains a Content-Disposition and a Content-Type with the correct form-data values. Even if the payload would be empty I wouldn't know why. Any way to inspect if it actually sends a file and not just a filename? Logging the file to the console before sending it give me a size in bytes, but that's all I got.

    – pjominet
    Mar 6 at 8:58












  • There is a typo in your code: const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data'); --> "mulipart"

    – hugo
    Mar 6 at 18:06











  • I check against my dotnet code: public Task<IActionResult> Backup(IFormFile file) Maybe you should remove FromForm option because it's convention based ('file' in the payload will match 'file' in the parameters)

    – hugo
    Mar 6 at 18:07






  • 1





    Fund my error (thanks to @hugo) i took a closer look at my headers and there wasn't just a typo, but a mistake too. It has to be Content-Disposition not Content-Type

    – pjominet
    Mar 7 at 9:01
















When you look at the network tab of your browser, does it send your file? Just to check if the problem comes from your frontend or your backend...

– hugo
Mar 5 at 22:19





When you look at the network tab of your browser, does it send your file? Just to check if the problem comes from your frontend or your backend...

– hugo
Mar 5 at 22:19













yes it seems to send the file, at least the request payload contains a Content-Disposition and a Content-Type with the correct form-data values. Even if the payload would be empty I wouldn't know why. Any way to inspect if it actually sends a file and not just a filename? Logging the file to the console before sending it give me a size in bytes, but that's all I got.

– pjominet
Mar 6 at 8:58






yes it seems to send the file, at least the request payload contains a Content-Disposition and a Content-Type with the correct form-data values. Even if the payload would be empty I wouldn't know why. Any way to inspect if it actually sends a file and not just a filename? Logging the file to the console before sending it give me a size in bytes, but that's all I got.

– pjominet
Mar 6 at 8:58














There is a typo in your code: const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data'); --> "mulipart"

– hugo
Mar 6 at 18:06





There is a typo in your code: const headers = new HttpHeaders().append('Content-Type', 'mulipart/form-data'); --> "mulipart"

– hugo
Mar 6 at 18:06













I check against my dotnet code: public Task<IActionResult> Backup(IFormFile file) Maybe you should remove FromForm option because it's convention based ('file' in the payload will match 'file' in the parameters)

– hugo
Mar 6 at 18:07





I check against my dotnet code: public Task<IActionResult> Backup(IFormFile file) Maybe you should remove FromForm option because it's convention based ('file' in the payload will match 'file' in the parameters)

– hugo
Mar 6 at 18:07




1




1





Fund my error (thanks to @hugo) i took a closer look at my headers and there wasn't just a typo, but a mistake too. It has to be Content-Disposition not Content-Type

– pjominet
Mar 7 at 9:01





Fund my error (thanks to @hugo) i took a closer look at my headers and there wasn't just a typo, but a mistake too. It has to be Content-Disposition not Content-Type

– pjominet
Mar 7 at 9:01












1 Answer
1






active

oldest

votes


















0














Problem solved:



in service.ts it should be




const headers = new HttpHeaders().append('Content-Disposition', 'multipart/form-data');




instead of




const headers = new HttpHeaders().append('Content-Type', 'multipart/form-data');




Also in the .net controller, adding or removing [FromForm(Name = "file")] as parameter prefix does not change the behavior. It works perfectly fine with or without it. As hugo pointed out in the comments it's convention based as long as the param name matches to name in the form data.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55008484%2fnet-core-2-2-angular-7-iformfile-in-file-upload-controller-is-always-null%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Problem solved:



    in service.ts it should be




    const headers = new HttpHeaders().append('Content-Disposition', 'multipart/form-data');




    instead of




    const headers = new HttpHeaders().append('Content-Type', 'multipart/form-data');




    Also in the .net controller, adding or removing [FromForm(Name = "file")] as parameter prefix does not change the behavior. It works perfectly fine with or without it. As hugo pointed out in the comments it's convention based as long as the param name matches to name in the form data.






    share|improve this answer



























      0














      Problem solved:



      in service.ts it should be




      const headers = new HttpHeaders().append('Content-Disposition', 'multipart/form-data');




      instead of




      const headers = new HttpHeaders().append('Content-Type', 'multipart/form-data');




      Also in the .net controller, adding or removing [FromForm(Name = "file")] as parameter prefix does not change the behavior. It works perfectly fine with or without it. As hugo pointed out in the comments it's convention based as long as the param name matches to name in the form data.






      share|improve this answer

























        0












        0








        0







        Problem solved:



        in service.ts it should be




        const headers = new HttpHeaders().append('Content-Disposition', 'multipart/form-data');




        instead of




        const headers = new HttpHeaders().append('Content-Type', 'multipart/form-data');




        Also in the .net controller, adding or removing [FromForm(Name = "file")] as parameter prefix does not change the behavior. It works perfectly fine with or without it. As hugo pointed out in the comments it's convention based as long as the param name matches to name in the form data.






        share|improve this answer













        Problem solved:



        in service.ts it should be




        const headers = new HttpHeaders().append('Content-Disposition', 'multipart/form-data');




        instead of




        const headers = new HttpHeaders().append('Content-Type', 'multipart/form-data');




        Also in the .net controller, adding or removing [FromForm(Name = "file")] as parameter prefix does not change the behavior. It works perfectly fine with or without it. As hugo pointed out in the comments it's convention based as long as the param name matches to name in the form data.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 7 at 9:08









        pjominetpjominet

        257




        257





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55008484%2fnet-core-2-2-angular-7-iformfile-in-file-upload-controller-is-always-null%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко