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?
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 () {
};
});
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
}