Zoeken op website

javascript - Hoe bestanden te verzenden van Angular 2 naar API


Ik heb onderstaande code op mijn pagina en probeer bestanden te uploaden via de WEB API. Ik heb geprobeerd de bestanden in formData naar de WEB API te sturen, maar ik weet niet hoe ik bestanden kan lezen die in formData zijn verzonden.

Hoe kan ik bestanden verzenden vanuit Angular naar een WEB API en hoe kan ik ze lezen in de API?

Angular2 frontend gedeelte

<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>

Angular2-component

@ViewChild("fileInput") fileInput;

addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];
        this.uploadService
            .upload(fileToUpload)
            .subscribe(res => {
                console.log(res);
            });
    }
}

Angular2 Upload Service

upload(fileToUpload: any) {
 
// var input =?? ; How can I send files to WEBAPI controller action.
    return this.http
        .post("/api/uploadFile", input);
}

WEB-API

[HttpPost]
    public string uploadFile()
    {
   // How can I handle files which are sent from UI
        return "uploaded";
    }

Antwoord #1

Op de frontend sturen we het bestand:

this.uploadService
    .upload(theFile)
    .subscribe(
        res => console.log('Uploaded file with content:', res),
        err => console.error('Failed with error:', error)
    );

In de dienst:

upload(fileToUpload) {
    return this.http.post('api/file/endpoint',
        fileToUpload,
        new HttpHeaders().set('Content-Type', 'application/octet-stream')
    )
    .map(res => res.text()); //mapping to text just to see the string response propagated to component subscribe
}

ASP.NET-controller

[Route("api/file/endpoint")]
[HttpPost]
public string GetFile()
{
    using (var stream = new StreamReader(Request.Body))
    {
        return stream.ReadToEnd();
    }
}

Je kunt natuurlijk ook andere manieren gebruiken om de stream te verwerken, inclusief asynchrone.