Home > OS >  How can I upload image to server in flutter?
How can I upload image to server in flutter?

Time:09-15

How can I upload image to server in flutter?

enter image description here

CodePudding user response:

var formData = FormData.fromMap({
  'name': 'wendux',
  'age': 25,
  'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),
  'files': [
    await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt'),
    await MultipartFile.fromFile('./text2.txt', filename: 'text2.txt'),
  ]
});
var response = await dio.post('/info', data: formData);

you can use. 'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),

CodePudding user response:

Used below plugings for this project

  get: ^4.6.5
  get_storage: 2.0.3
  dio: ^4.0.6
  cached_network_image: ^3.0.0
  image_picker: ^0.8.5 3
  flutter_svg: 1.1.5

*Please try this. This is main.dart *

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_upload/controller.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Image Upload',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ProfileController profilerController = Get.put(ProfileController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          decoration: BoxDecoration(
            boxShadow: <BoxShadow>[
              BoxShadow(
                color: Colors.grey.withOpacity(0.3),
                blurRadius: 40,
              ),
            ],
          ),
          child: SizedBox(
            height: 115,
            width: 115,
            child: Stack(
              fit: StackFit.expand,
              // overflow: Overflow.visible,
              children: [
                Obx((){
                  if(profilerController.isLoading.value){
                    return CircleAvatar(
                      backgroundImage: AssetImage('assets/icons/no_user.jpg'),
                      child: Center(
                          child: CircularProgressIndicator(
                            backgroundColor: Colors.white,
                          )),
                    );
                  } else {
                    if(profilerController.imageURL.length != 0){
                      return CachedNetworkImage(
                        imageUrl: profilerController.imageURL,
                        fit: BoxFit.cover,
                        imageBuilder: (context, imageProvider) => CircleAvatar(
                          backgroundColor: Colors.white,
                          backgroundImage: imageProvider,
                        ),
                        placeholder: (context, url) => CircleAvatar(
                          backgroundImage: AssetImage('assets/icons/no_user.jpg'),
                          child: Center(
                              child: CircularProgressIndicator(
                                backgroundColor: Colors.white,
                              )),
                        ),
                        errorWidget: (context, url, error) => Icon(Icons.error),
                      );
                    } else {
                      return CircleAvatar(
                        backgroundImage: AssetImage('assets/icons/no_user.jpg'),
                      );
                    }
                  }
                }),
                Positioned(
                  right: -16,
                  bottom: 0,
                  child: SizedBox(
                    height: 46,
                    width: 46,
                    child: FlatButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50),
                        side: BorderSide(color: Colors.white),
                      ),
                      color: Colors.grey[200],
                      onPressed: () {
                        Get.bottomSheet(
                          Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(16.0),
                                  topRight: Radius.circular(16.0)),
                            ),
                            child: Wrap(
                              alignment: WrapAlignment.end,
                              crossAxisAlignment: WrapCrossAlignment.end,
                              children: [
                                ListTile(
                                  leading: Icon(Icons.camera),
                                  title: Text('Camera'),
                                  onTap: () {
                                    Get.back();
                                    profilerController.uploadImage(ImageSource.camera);
                                  },
                                ),
                                ListTile(
                                  leading: Icon(Icons.image),
                                  title: Text('Gallery'),
                                  onTap: () {
                                    Get.back();
                                    profilerController
                                        .uploadImage(ImageSource.gallery);
                                  },
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                      child: SvgPicture.asset("assets/icons/Camera Icon.svg"),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      )
    );
  }
}

this is controller.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter_image_upload/service.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class ProfileController extends GetxController {
  var isLoading = false.obs;
  var imageURL = '';

  void uploadImage(ImageSource imageSource) async {
    try {
      final pickedFile = await ImagePicker().getImage(source: imageSource);
      isLoading(true);
      if (pickedFile != null) {
        var response = await ImageService.uploadFile(pickedFile.path);

        if (response.statusCode == 200) {
          //get image url from api response
          imageURL = response.data['user']['image'];

          Get.snackbar('Success', 'Image uploaded successfully',
              margin: EdgeInsets.only(top: 5,left: 10,right: 10));
        } else if (response.statusCode == 401) {
          Get.offAllNamed('/sign_up');
        } else {
          Get.snackbar('Failed', 'Error Code: ${response.statusCode}',
              margin: EdgeInsets.only(top: 5,left: 10,right: 10));
        }
      } else {
        Get.snackbar('Failed', 'Image not selected',
            margin: EdgeInsets.only(top: 5,left: 10,right: 10));
      }
    } finally {
      isLoading(false);
    }
  }
}

this is service.dart

import 'package:dio/dio.dart';

class ImageService{
  static Future<dynamic> uploadFile(filePath) async {
    //jwt authentication token
    var authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNhbTEyM0BnbWFpbC5jb20iLCJzdWIiOiI2MDViOTgxZDRkOTk4YjMxMjRhODEyMDQiLCJyb2xlIjoiY3VzdG9tZXIiLCJpYXQiOjE2MTgyMzQ4NjUsImV4cCI6MTYxODMyMTI2NX0.lYUfZ20TlFZZQO_1JKZbKYZublPRoejqnmxKOAM9CN0';
    //user im use to upload image
    //Note: this authToken and user id parameter will depend on my backend api structure
    //in your case it can be only auth token
    var _userId = '605b981d4d998b3124a81204';

    try {
      FormData formData =
      new FormData.fromMap({
        "image":
        await MultipartFile.fromFile(filePath, filename: "dp")});

      Response response =
      await Dio().put(
          "https://appointella-api.herokuapp.com/customer/$_userId",
          data: formData,
          options: Options(
              headers: <String, String>{
                'Authorization': 'Bearer $authToken',
              }
          )
      );
      return response;
    }on DioError catch (e) {
      return e.response;
    } catch(e){
    }
  }
}

CodePudding user response:

Select Image from Gallery using File Picker

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
class ImageScreen extends StatefulWidget {
  ImageScreen();
  @override
  State<ImageScreen> createState() => _ImageScreenState();
}

class _ImageScreenState extends State<ImageScreen> {
  File file;

  Future<File> uploadImage() async {
    FilePickerResult result = await FilePicker.platform.pickFiles();

    if (result != null) {
      setState(() {
        file = File(result.files.single.path);
      });
      print(result.files.single.path);

    } else {
      // User canceled the picker
    }
    return file;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          uploadImage();
        },
        child: Container(
          color: Colors.green,
          padding: EdgeInsets.all(5),
          child: Text('Upload Image', style: TextStyle(fontSize: 16, color: Colors.white),)
        ),
      ),
    );
  }
}

Uploading Image to the server using http.multipartFile

  static Future<dynamic> uploadImage({File file}) async {
    try {
      http.MultipartRequest request = new http.MultipartRequest("POST", _uri);
      http.MultipartFile multipartFile = await http.MultipartFile.fromPath('file_name', file.path);
      request.files.add(multipartFile);
      var streamedResponse = await request.send();
      var response = await http.Response.fromStream(streamedResponse);
      if (response.statusCode == 200 ) {
        return jsonDecode(response.body);
      }
    }
    catch (e) {
      return null;
    }
  }

CodePudding user response:

add dependencies image_picker: ^0.8.5 3 http: ^0.13.5

add this in your class import 'package:http/http.dart' as http;

use image_picker to select file and post that imageFilePath using http package

  • Related