Kreal
Kreal

Reputation: 85

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.

Upvotes: 4

Views: 13721

Answers (2)

Kalju Pärn
Kalju Pärn

Reputation: 31

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;

Upvotes: 0

Nishan
Nishan

Reputation: 4441

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;
  }

Upvotes: 9

Related Questions