I'm not able to get a file from my Angular 11 application uploaded to my .NET 5 service. If I set a breakpoint at the first line of the controller method it's not hit. The angular app just gets an HttpErrorResponse
with a status of 0. I'm able to POST
without issue to other methods in this same controller, so I know all the "setup" type stuff is working properly.
I'm doing the upload like so on the Angular side:
postUploadLegacyData(files: File[]): Observable<string[]> {
const formData = new FormData()
files.forEach(x => formData.append('file', x, x.name))
return this.http.post<string[]>('requests/import', formData)
}
and then on the .NET side I have this:
[Route("[controller]"), Produces("application/json"), Authorize, ApiController]
public class RequestsController : ControllerBase
{
[HttpPost("import")]
[Consumes("multipart/form-data")]
public IActionResult PostImportExistingRequests(IEnumerable<IFormFile> files)
I found that it should instead be this on the server side:
public async Task<IActionResult> PostImportExistingRequestsAsync()
{
var form = await Request.ReadFormAsync();
var files = form.Files;
Angular: scaffold a front end folder angular for your component ng g component upload --spec false
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { HttpEventType, HttpClient } from '@angular/common/http';
@Component({
selector: 'file-upload-toAspCore',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {
public progress: progressPercentage; // you can yse this to display progress in HTML
public message: string;
@Output() public onUploadFinished = new EventEmitter();
constructor(private http: HttpClient) { }
ngOnInit() {}
public uploadFile = (files) => {
if (files.length === 0) {
return;
}
let filesToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', filesToUpload, filesToUpload.name);
this.http.post('https://localhost:4200/api/uploaderAction', formData,
{reportProgress: true, observe: 'events'})
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress)
// helps display progress to user
this.progress = Math.round(100 * event.loaded / event.total);
else if (event.type === HttpEventType.Response) {
this.message = 'Upload success.';
this.onUploadFinished.emit(event.body);
}
});
}
}
ASP Action that receives the file
[HttpPost, DisableRequestSizeLimit]
public async Task<IActionResult> UploaderAction()
{
try
{
var formCollection = await Request.ReadFormAsync();
var file = formCollection.Files.First();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.