2

I am using ald angularJs and trying upload file and do API call, API is a .net core app, I can see request using breakpoint in the API but parameter is comes null always.

here is the angularJs code

 vm.uploadMotorFactor = function () {
   let uploadUrl = `/api/Membership/UploadMotorFactor`;

   let fileInput = document.getElementById('motorFactorFile');
   let file = fileInput.files[0];

   if (!file) {
     alert("Please select a CSV file to upload.");
     return;
   }

   let formData = new FormData();
   formData.append('file', file); // Matches the property name in ImportFileDataRequest

   $http.post(uploadUrl, formData, {
     headers: { 'Content-Type': undefined }, // Let the browser set the correct multipart boundary
     transformRequest: angular.identity
   }).then(response => {
     alert('File uploaded successfully!');
     fileInput.value = ''; // Clear the file input after successful upload
   }).catch(error => {
     console.error('Error uploading file:', error);
     alert('File upload failed.');
   });
 };

this is my API endpoint

 [HttpPost]
 public async Task<IActionResult> UploadMotorFactor([FromForm] IFormFile file)
 {
     try
     {
         return file != null ? Ok() : StatusCode(StatusCodes.Status500InternalServerError);
        
     }
     catch (Exception e)
     {
         _logger.LogError(e, "Failed to download Motor factor");
         return StatusCode(StatusCodes.Status500InternalServerError);
     }
 }

I used 'Content-Type', 'multipart/form-data' as well but the result is the same, what I am missing here?

enter image description here

it is an old angularjs and looks like this:


<input type="file" id="motorFactorFile"  />
 <button class="btn btn-success" ng click="vm.uploadMotorFactor()">Upload</button>

this is the js file:

const mycommadashboard = angular.module("umbraco");

mycommadashboard.controller("MyDashboardController",
  function ($scope, $http, $timeout, Upload) {
    let vm = this;
    vm.uploadMotorFactor = function () {
      
    };

  });
1
  • I found the way using build in 'Upload' function like Upload.upload({ url: uploadUrl, file: file }) but this way is other issue exists I can send the file and get in the API parameter but if I add one more parameter for example one file to upload and other one email or some model, second parameter or model is not binded in the c# api Commented Mar 5 at 6:52

2 Answers 2

1

Please try to use onFileSelected event, it works for me.

enter image description here

Test Code

upload.component.html

<h2>Upload file</h2>
<input type="file" id="motorFactorFile" (change)="onFileSelected($event)">
<button (click)="uploadFile()">Upload file</button>

upload.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.css']
})
export class UploadComponent {
  selectedFile: File | null = null;
  message: string = '';

  constructor(private http: HttpClient) {}

  onFileSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      this.selectedFile = input.files[0];
    }
  }

  uploadFile() {
    if (!this.selectedFile) {
      this.message = 'Please select one file!';
      return;
    }

    const formData = new FormData();
    formData.append('file', this.selectedFile);

    this.http.post('https://localhost:7181/Test', formData).subscribe({
      next: (res) => {
        this.message = 'upload success!';
      },
      error: (err) => {
        this.message = 'failed, please check backen API logs!';
        console.error(err);
      }
    });
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

it is an old angularjs and looks like this: const mycommadashboard = angular.module("umbraco"); mycommadashboard.controller("MyDashboardController", function ($scope, $http, $timeout, Upload) { let vm = this; vm.uploadMotorFactor = function () { }; }); input type="file" id="motorFactorFile" /> <button class="btn btn-success" ng-click="vm.uploadMotorFactor()"> Upload </button>
Hi @Sargis, could you share the http trace, it can help us investigate the issue.
hi @Jason I updated my question and added some clarification, could you check it
0

Here is the solution https://our.umbraco.com/forum/extending-umbraco-and-using-the-api/81065-file-upload-in-backoffice-custom-section

 let fileInput = document.getElementById(`ImageFile`);
  let file = fileInput.files[0];

$http({
    method: 'POST',
    url: "/umbraco/backoffice/api/myController/Create",
    headers: { 'Content-Type': undefined }, // Let the browser set multipart/form-data boundaries
    transformRequest: function () {
      var formData = new FormData();
      if (file) {
        formData.append("file", file);
      }
      formData.append("competition", JSON.stringify(vm.competition)); // Send competition object as string
      return formData;
    }
  })

this is an .net API action method

[HttpPost]
public async Task<IActionResult> Create([FromForm] IFormFile file, [FromForm] string competition)
{
 var competitionData = JsonConvert.DeserializeObject<CompetitionRequest>(competition);
// do service call
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.