Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload file into ASP.NET Core Web API

We have a front-end flutter application, which should send file to our backend (ASP.NET Core Web API). The question is: how should controller be constructed? I believe that it should be a POST-method, but how to get this file on the backend.

P.S. All requests come to our API in JSON format.

like image 227
Kreal Avatar asked Oct 30 '25 19:10

Kreal


1 Answers

In dotnet core controller you can use IFormFile Interface to get files,

[HttpPost("upload-file")]
public async Task<IActionResult> UploadFile([FromQuery] IFormFile file){
    
    if(file.Length > 0){
       // Do whatever you want with your file here
       // e.g.: upload it to somewhere like Azure blob or AWS S3
    }

    //TODO: Save file description and image URL etc to database.
}

In Flutter you need to send a Multipart POST request to include files with binary content (images, various documents, etc.), in addition to the regular text values.

import 'package:http/http.dart' as http;

  Future<String> uploadImage(filename, url) async {
    var request = http.MultipartRequest('POST', Uri.parse(url));
    request.files.add(
     http.MultipartFile.fromBytes(
      'file',
      File(filename).readAsBytesSync(),
      filename: filename.split("/").last
      )
    );
    var res = await request.send();
    return res;
  }
like image 198
Nishan Avatar answered Nov 02 '25 10:11

Nishan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!