how-to-upload-images-files-in-flutter-and-store-them-in-odoo-backend

How to Upload Images & Files in Flutter and Store Them in Odoo Backend?

In the age of smartphones and mobile apps, uploading images and files has become a common feature in many applications. Whether you’re developing an e-commerce app where users must upload profile pictures, invoices, or receipts or perhaps a logistics app where documents must be submitted for verification, handling file uploads is crucial. But how do you make this process seamless for your users, and how do you store those files in a backend system that’s both reliable and scalable?

In this blog post, we’ll walk you through handling file uploads in a Flutter app and securely storing them in an Odoo backend. Don’t worry if you’re new to either Flutter or Odoo – this guide is designed to be beginner-friendly and approachable.

The Importance of File Uploads in Modern Apps

File uploads are essential for modern apps – users must submit documents, images, or other files that must be stored safely. For example, in an e-commerce app, users might need to upload product images, invoices, or delivery receipts. For logistics, uploaded documents might include shipping labels or proof of delivery. Flutter, the framework used for building natively compiled mobile, web, and desktop applications from a single codebase, makes handling these tasks relatively simple.

Meanwhile, Odoo, an open-source ERP system, provides an easy-to-use backend for storing and managing such files. With its robust API, Odoo allows you to store images, documents, and other files, all while keeping everything neatly organized.

In this tutorial, we’ll guide you step by step through:

  1. Setting up the Flutter project for file uploads.
  2. Using the Flutter app to select images and files.
  3. Sending files to Odoo backend using their REST API.
  4. Handling the server’s response and displaying uploaded files within the Flutter app.

So whether you’re a beginner or a developer looking to add this functionality, you’ll find everything you need here.

1. Setting up the flutter project

Before headfirst into file uploads, let’s set up a Flutter project. If you haven’t already created one, you can do so by running:

				
					Add the required dependencies in pubspec.yaml
				
			
				
					dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  get: ^4.7.2
  hive_flutter: ^1.1.0
  file_picker: ^10.1.2
  image_picker: ^1.1.2
  dio: ^5.8.0+1



				
			

2. Selecting images and files in Flutter

In this step, we’ll allow users to select files (images or documents) from their devices. We’ll use the image_picker package for pictures and the file_picker package for documents.

Start by creating a service file called file_picker_service.dart, where we’ll implement methods for picking files.

				
					Create a service file file_picker_service.dart
				
			
				
					import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';

class FilePickerService {
  static Future<File?> pickImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      return File(image.path);
    }
    return null;
  }

  static Future<File?> pickFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null && result.files.single.path != null) {
      return File(result.files.single.path!);
    }
    return null;
  }
}

				
			

In this service, we have two methods:

  • pickImage() allows the user to choose an image from their device’s gallery.
  • pickFile() lets the user select any file (such as PDFs or Word documents).

Now, we’ve got a service that lets users select files or images – easy enough, right?

3. Sending them to Odoo’s REST API

Once a file is selected, we must send it to Odoo for storage. We will create an API call to Odoo’s backend using the http package.

				
					Create odoo_upload_service.dart to handle file uploads.
				
			
				
					import 'dart:io';
import 'package:dio/dio.dart';

class OdooUploadService {
  final String baseUrl = "https://your-odoo-instance.com";
  final String uploadEndpoint = "/web/dataset/call_kw/your.model/create";

  Future<void> uploadFile(File file, String fileName, String accessToken) async {
    try {
      Dio dio = Dio();
      dio.options.headers["Authorization"] = "Bearer $accessToken";


      FormData formData = FormData.fromMap({
        "jsonrpc": "2.0",
        "params": {
          "model": "your.model",
          "method": "create",
          "args": [
            {
              "name": fileName,
              "file": await MultipartFile.fromFile(file.path, filename: fileName),
            }
          ],
        }
      });


      Response response = await dio.post("$baseUrl$uploadEndpoint", data: formData);


      if (response.statusCode == 200) {
        print("File uploaded successfully: ${response.data}");
      } else {
        print("Failed to upload file: ${response.data}");
      }
    } catch (e) {
      print("Upload error: $e");
    }
  }
}

				
			

In this service:

  • The uploadFile method sends a file to your Odoo instance using a multipart HTTP request.
  • We include the model (the Odoo model where the file is being uploaded) and recorded (the specific record to which the file should be attached).
  • The Authorization header includes your Odoo API key for secure access.

Replace the odooUrl and odooApiKey variables with your actual Odoo instance URL and API key.

4. Handling Odoo responses and displaying files

Once the file is successfully uploaded to Odoo, it’s time to display the results in the Flutter app. Let’s create a simple UI for uploading files and showing the upload status.

  1. Implementing File Upload in the UI
				
					Create upload_screen.dart
				
			
				
					import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';


import 'file_picker_service.dart';
import 'odoo_upload_service.dart';


class UploadScreen extends StatefulWidget {
  @override
  _UploadScreenState createState() => _UploadScreenState();
}


class _UploadScreenState extends State<UploadScreen> {
  File? selectedFile;
  final OdooUploadService _uploadService = OdooUploadService();
  final String accessToken = "your_odoo_access_token";


  void pickImage() async {
    File? file = await FilePickerService.pickImage();
    if (file != null) {
      setState(() {
        selectedFile = file;
      });
    }
  }


  void pickFile() async {
    File? file = await FilePickerService.pickFile();
    if (file != null) {
      setState(() {
        selectedFile = file;
      });
    }
  }


  void uploadFile() async {
    if (selectedFile != null) {
      await _uploadService.uploadFile(
          selectedFile!, "uploaded_file.png", accessToken);
      Get.snackbar("Success", "File uploaded to Odoo!");
    } else {
      Get.snackbar("Error", "Please select a file first!");
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Upload to Odoo")),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          selectedFile != null
              ? Image.file(selectedFile!, height: 150)
              : Text("No file selected"),
          SizedBox(height: 20),
          ElevatedButton(onPressed: pickImage, child: Text("Pick Image")),
          ElevatedButton(onPressed: pickFile, child: Text("Pick File")),
          ElevatedButton(onPressed: uploadFile, child: Text("Upload File")),
          
        ],
      ),
    );
  }
}




				
			

2. Displaying Uploaded Files in Flutter

      a. If you want to fetch and display uploaded files from Odoo, modify  

				
					odoo_upload_service.dart
				
			
				
					Future<List<String>> fetchUploadedFiles(String accessToken) async {
    try {
      Dio dio = Dio();
      dio.options.headers["Authorization"] = "Bearer $accessToken";


      Response response =
          await dio.get("https://your-odoo-instance.com/api/files");


      if (response.statusCode == 200) {
        List<String> fileUrls = (response.data as List)
            .map((file) => file["url"].toString())
            .toList();
        return fileUrls;
      } else {
        return [];
      }
    } catch (e) {
      print("Fetch error: $e");
      return [];
    }
  }


				
			

Now, modify upload_screen.dart to display uploaded files.

				
					FutureBuilder<List<String>>(
            future: _uploadService.fetchUploadedFiles(accessToken),
            builder: (context, snapshot) {
              if (!snapshot.hasData) return CircularProgressIndicator();
              return Column(
                children: snapshot.data!
                    .map((fileUrl) => Image.network(fileUrl))
                    .toList(),
              );
            },
          ),

				
			

A Complete Guide to Uploading Files in Flutter and Storing Them in Odoo Backend

In this tutorial, we’ve walked through uploading images and files from a Flutter app to an Odoo backend, providing a simple, step-by-step guide. We covered all the key points, from selecting files in FlutterFlutterFlutter to sending them via Odoo’s REST API and displaying the upload status.

With this functionality, you can easily add file upload features to your Flutter apps and Utilize Odoo backend to store and manage those files. Whether you’re working on an e-commerce app, a logistics solution, or any other project that requires file uploads, this guide has hopefully given you the foundation you need to get started.

Happy coding, and good luck with your Flutter and Odoo project!

Picture of Irshad

Irshad

I’m Irshad, a passionate self-taught Flutter Developer Intern with strong problem-solving skills and a drive for continuous learning. I have experience building responsive user interfaces, implementing complex features, and collaborating effectively within teams.

Get a free quote