Using Supabase to Store Images in a .NET Application

Aroge Ridwan - Jun 3 - - Dev Community

Table of Contents

Introduction

Supabase storage offers a powerful solution for efficiently managing file storage in web applications. In this guide, we'll explore how to leverage Supabase storage within a .NET application to handle image uploads seamlessly.

By using Supabase storage, we can avoid the pitfalls of storing large files directly within the database, which can adversely affect database performance and scalability. Instead, Supabase converts uploaded files into accessible URLs, which are then stored in the database. This approach not only helps maintain a lean and efficient database but also simplifies the process of accessing and integrating files into your application.

In this tutorial, we'll walk through the steps to set up a .NET API that allows users to upload images. These images will be stored securely in Supabase storage, and their URLs will be gotten which can later be stored in the database for easy retrieval and integration into your application. Let's dive in and discover how Supabase storage can streamline image management in your .NET projects.

Set Up Supabase Storage

Step 1: Sign up at supabase.com and create a new project.

Project Details

  • Name: Enter a name for your project.

  • Database Password: Create a strong password for your database. This password will be used to connect to your database, so ensure it is secure.

  • Region: Choose a region for your database server. If you are in Nigeria, the closest region is typically Europe (London). Selecting a closer region can help minimize latency for users in Nigeria.

Click on the Create new project button to finalize the creation of your new Supabase project.

create supabase project

Step 2: Create a Bucket in the new project

  • Click on the Storage tab on the left-hand menu.

  • Click the New Bucket button.

  • Enter a name for your new bucket, e.g., photos.

  • Toggle the switch to make the bucket public. This setting allows anyone to access the files in this bucket without needing authentication.

  • Click the Save button to save your new bucket.

Add New bucket

Create a .NET Project Using Visual Studio

  • Launch Visual Studio.
  • Click on Create a new project .
  • Search for ASP.NET Core Web API and select it.
  • Enter a name for your project (e.g., SupabaseImageUpload).
  • Choose a location to save your project.
  • select the target framework (e.g., .NET 6.0 or .NET 7.0 or .NET 8.0).
  • Click Create .

Configure Supabase Client

Step 1: Install the necessary NuGet packages:

  • Open your project in Visual Studio.
  • Right-click on your project in the Solution Explorer.
  • Select Manage NuGet Packages...
  • Search for Supabase and select the Supabase package from the list.
  • Click the Install button and ensure that the Supabase package is listed among the installed packages. Install supabase

Step 2: Configure Supabase in appsettings.json

 "Supabase": {
    "Url": "https://your-supabase-url.supabase.co",
    "ApiKey": "your-supabase-api-key"
  }
Enter fullscreen mode Exit fullscreen mode
  • Click on the Settings tab on the left-hand menu and then click on API
  • Copy the URL provided under the API settings and paste in the Url in the appsettings.json
  • Click on the service_role secret to reveal it, Copy the API key (secret) provided and paste in the Apikey in the appsettings.json

appsettings

Step 3: Program.cs Configuration

builder.Services.AddScoped<Supabase.Client>(_ =>
new Supabase.Client(
    builder.Configuration["Supabase:Url"],
    builder.Configuration["Supabase:ApiKey"],
    new SupabaseOptions
    {
        AutoRefreshToken = true,
        AutoConnectRealtime = true,
    }));
Enter fullscreen mode Exit fullscreen mode

Step 4:
Create a model for the request. Add CreateImageRequest.cs

 public class CreateImageRequest
 {
     public string Name { get; set; }
     public IFormFile Image { get; set; }
 }
Enter fullscreen mode Exit fullscreen mode

Step 5: Create a controller ImageController.cs:

 [Route("api/[controller]")]
 [ApiController]
 public class ImageController : Controller
 {
     [HttpPost]
     public async Task<IActionResult> UploadImage([FromForm] CreateImageRequest request,
          [FromServices] Supabase.Client client)
     {
         using var memoryStream = new MemoryStream();
         await request.Image.CopyToAsync(memoryStream);
         var imageBytes = memoryStream.ToArray();

         var bucket = client.Storage.From("photos");
         var fileName = $"{Guid.NewGuid()}_{request.Image.FileName}";
         await bucket.Upload(imageBytes, fileName);

         var publicUrl = bucket.GetPublicUrl(fileName);

         return Ok(new { Url = publicUrl });
     }
 }
Enter fullscreen mode Exit fullscreen mode

Step 6: Test and Run your .NET application

  • Use a tool like Postman or Swagger to test the image upload endpoint:
  • URL: https://your-localhost/api/Image
  • Method: POST
  • Form Data: Name: Any string value. Image: Choose an image file to upload.

End result

final result

Conclusion

In this article, you've successfully set up a .NET API that can upload images to Supabase storage and retrieve their public URLs. This can be extended and integrated into various applications where you need to store and manage images or other files. Supabase provides a robust backend solution with easy integration for your .NET applications.
Here is the GitHub repository for this article in case you need to check it out. Lastly, if you have found value in this article, please consider sharing it with your peers who may also benefit from it.

What are your thoughts on the topic "Using Supabase to Store Images in a .NET Application"? Feel free to share your thoughts in the comments section below.

Happy coding!

. .