admin管理员组文章数量:1287598
I am using ald angularJs and trying upload file and do API call, API is a 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 () {
};
});
I am using ald angularJs and trying upload file and do API call, API is a 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 () {
};
});
Share
Improve this question
edited yesterday
Sargis
asked Feb 24 at 16:01
SargisSargis
1472 silver badges9 bronze badges
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 – Sargis Commented yesterday
1 Answer
Reset to default 0Please try to use onFileSelected
event, it works for me.
Test Code
uploadponent.html
<h2>Upload file</h2>
<input type="file" id="motorFactorFile" (change)="onFileSelected($event)">
<button (click)="uploadFile()">Upload file</button>
uploadponent.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-upload',
templateUrl: './uploadponent.html',
styleUrls: ['./uploadponent.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);
}
});
}
}
本文标签: javascriptAngularJs API post file to the net core app endpoint file parameter is nullStack Overflow
版权声明:本文标题:javascript - AngularJs API post file to the .net core app endpoint file parameter is null - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741254687a2366441.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论