4

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.

2
  • 1
    A Post is when there is a body in the send Request (it can be either a client sending to a server or a server sending to a client). A controller is use to parse the receive message (either a message from a server at the client, or a message from a client at the server). The controller is always parsing a GET (not a Post) to answer your question. Commented Apr 12, 2021 at 15:29
  • Maybe this can help : learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads Commented Apr 12, 2021 at 15:43

2 Answers 2

9

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;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank u very much!
Just FYI for anyone still struggling, although 'filename' is an optional parameter in the fromBytes function, please don't wrongly assume (like I did) that it is actually optional. The IFormFile parameter will show up as null otherwise.
0

F# file upload took few hours to figure out giraffe and HTML when some other data need to be added + drag-drop

Here is code:

  script [ _type "text/javascript"; _src "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ] [];
  script [ _type "text/javascript"] [ rawText "
     $(function() { $('#uploadForm').submit(function() {
        if(!$('form input[type=file]').val()) {
           alert('You must select a file!'); 
           return false;
        };});}); "];
  form [_method "POST"; _action "/upload"; 
      _enctype "multipart/form-data"; _id "uploadForm"; _name "uploadForm"] 
    h2 [] [ Text "Drop or select file to upload" ];
    [ input [ _type "file"; _name "fileName"; _id "file"; ]; 
      input [ _type "text"; _name "Title";];
      button [ _type "submit"] [ str "Uppload" ];
    ];

and

let fileUploadHandler = fun (next : HttpFunc) (ctx : HttpContext) -> task {
        return!
            (match ctx.Request.HasFormContentType with
            | false -> RequestErrors.BAD_REQUEST ("Bad file uppload request") 
            | true  ->
                let title = (ctx.Request.Form.Item("Title").ToString()) in
                let file = ctx.Request.Form.Files |> Seq.head in
                let fileName = file.FileName in
                let stream = new MemoryStream() in
                file.CopyTo( stream);
                let content = Encoding.UTF8.GetString(stream.ToArray()) in
                let db_ctx = mssql.GetDataContext() in
                let row = db_ctx.Dbo.File.Create(content, fileName, title) in
                db_ctx.SubmitUpdates();
                htmlView indexView  
                ) 
                next ctx
        }

POST >=> route "/upload" >=> fileUploadHandler;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.