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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With