Flutter / GetX Basics / File Uploading
File Upload
-
Steps
1. pubspec.yaml
dependencies: flutter: sdk: flutter http: ^0.14.0 2. File Upload Functionality:
import 'package:get/get.dart'; import 'package:http/http.dart' as http; class FileUploadController extends GetxController { Future uploadFile(String filePath) async { var url = 'YOUR_UPLOAD_URL'; // Replace with your server's upload URL var request = http.MultipartRequest('POST', Uri.parse(url)); request.files.add(await http.MultipartFile.fromPath('file', filePath)); try { var response = await request.send(); if (response.statusCode == 200) { // File uploaded successfully print('File uploaded'); } else { // Handle error response print('Error uploading file'); } } catch (e) { // Handle network and other errors print('Error: $e'); } } } 3. Use GetX Controller in Widget:
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'file_upload_controller.dart'; class FileUploadPage extends StatelessWidget { final FileUploadController _fileUploadController = Get.put(FileUploadController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('File Upload Example'), ), body: Center( child: ElevatedButton( onPressed: () async { // Replace 'filePath' with the actual path of the file you want to upload String filePath = '/path/to/your/file.ext'; await _fileUploadController.uploadFile(filePath); }, child: Text('Upload File'), ), ), ); } }