File upload for flutter

Anyone willing to help me figure out why i can’t upload file in 8 base using flutter?

I’m using the 8base for flutter . I’ve got normal queries and mutation working, no problem. but when using mutation for file upload getting error i don’t know why. if anyone have solution please guide me to solve this error

Here is the code:

import ‘dart:io’;

import ‘package:flutter/material.dart’;

import ‘package:graphql_flutter/graphql_flutter.dart’;

import ‘package:http/http.dart’;

import ‘package:http_parser/http_parser.dart’;

import ‘package:image_picker/image_picker.dart’;

// String get host => Platform.isAndroid ? ‘10.0.2.2’ : ‘localhost’;

const uploadImage = r"""

mutation($file: uploaded){

testCreate(data:{

image:{

  create:$file

  connect:{

    fileId:""

  }

}

}){

image{

  downloadUrl

  fileId

  shareUrl

}

}

}

“”";

// mutation($file: Upload!) {

// upload(file: $file)

// }

class MyAppUpload extends StatelessWidget {

@override

Widget build(BuildContext context) {

final HttpLink httpLink = HttpLink(

    uri: "<here is my api>",

    headers: {

      "authorization": "<here is my token>"

    }); //test3 token used of 8base

final ValueNotifier<GraphQLClient> client =

    ValueNotifier<GraphQLClient>(GraphQLClient(

        link: httpLink,

        cache: OptimisticCache(

          dataIdFromObject: typenameDataIdFromObject,

        )));

return MaterialApp(

  title: 'Flutter Demo',

  theme: ThemeData(

    primarySwatch: Colors.blue,

  ),

  home: GraphQLProvider(

    client: client,

    child: Scaffold(

      appBar: AppBar(

        title: Text("Graphql Upload Image Demo"),

      ),

      body: MyHomePage(),

    ),

  ),

);

}

}

class MyHomePage extends StatefulWidget {

MyHomePage();

@override

_MyHomePageState createState() => _MyHomePageState();

}

class _MyHomePageState extends State {

File _image;

bool _uploadInProgress = false;

_uploadImage(BuildContext context) async {

setState(() {

  _uploadInProgress = true;

});

var byteData = _image.readAsBytesSync();

var multipartFile = MultipartFile.fromBytes(

  'photo',

  byteData,

  filename: '${DateTime.now().second}.jpg',

  contentType: MediaType("image", "jpg"),

);

var opts = MutationOptions(

  document: uploadImage,

  variables: {

    "file": multipartFile,

  },

);

var client = GraphQLProvider.of(context).value;

var results = await client.mutate(opts);

setState(() {

  _uploadInProgress = false;

});

var message = results.hasException

    ? '${results.exception}'

    : "Image was uploaded successfully!";

final snackBar = SnackBar(content: Text(message));

Scaffold.of(context).showSnackBar(snackBar);

}

Future selectImage() async {

var image = await ImagePicker.pickImage(source: ImageSource.gallery);

setState(() {

  _image = image;

});

}

@override

Widget build(BuildContext context) {

return Container(

  child: Column(

    // mainAxisAlignment: MainAxisAlignment.center,

    mainAxisSize: MainAxisSize.max,

    children: <Widget>[

      if (_image != null)

        Flexible(

          flex: 9,

          child: Image.file(_image),

        )

      else

        Flexible(

          flex: 9,

          child: Center(

            child: Text("No Image Selected"),

          ),

        ),

      Flexible(

        child: Row(

          mainAxisAlignment: MainAxisAlignment.center,

          mainAxisSize: MainAxisSize.max,

          children: <Widget>[

            FlatButton(

              child: Row(

                mainAxisAlignment: MainAxisAlignment.center,

                mainAxisSize: MainAxisSize.min,

                children: <Widget>[

                  Icon(Icons.photo_library),

                  SizedBox(

                    width: 5,

                  ),

                  Text("Select File"),

                ],

              ),

              onPressed: () => selectImage(),

            ),

            if (_image != null)

              Mutation(

                  options: MutationOptions(

                    document: uploadImage,

                    onCompleted: (d) {

                      print(d);

                      setState(() {

                        _uploadInProgress = false;

                      });

                    },

                    update: (cache, results) {

                      var message = results.hasException

                          ? '${results.exception}'

                          : "Image was uploaded successfully!";

                      final snackBar = SnackBar(content: Text(message));

                      Scaffold.of(context).showSnackBar(snackBar);

                    },

                  ),

                  builder: (RunMutation runMutation, QueryResult result) {

                    return FlatButton(

                      child: _isLoadingInProgress(),

                      onPressed: () {

                        setState(() {

                          _uploadInProgress = true;

                        });

                        var byteData = _image.readAsBytesSync();

                        var multipartFile = MultipartFile.fromBytes(

                          'photo',

                          byteData,

                          filename: '${DateTime.now().second}.jpg',

                          contentType: MediaType(

                            "image",

                            "jpg",

                          ),

                        );

                        runMutation(<String, dynamic>{

                          "file": multipartFile,

                        });

                        print(byteData);

                        print(multipartFile.filename);

                        print(multipartFile.contentType);

                        print(multipartFile.length);

                        print(multipartFile.field);

                        print("sanket");

                      },

                    );

                    // onCompleted:

                    // (d) {

                    //   print(d);

                    //   setState(() {

                    //     _uploadInProgress = false;

                    //   });

                    // };

                    // update:

                    // (cache, results) {

                    //   var message = results.hasErrors

                    //       ? '${results.errors.join(", ")}'

                    //       : "Image was uploaded successfully!";

                    //   final snackBar = SnackBar(content: Text(message));

                    //   Scaffold.of(context).showSnackBar(snackBar);

                    // };

                    // if (_image != null)

                    //   FlatButton(

                    //       child: _isLoadingInProgress(),

                    //       onPressed: () => _uploadImage(context));

                  }),

          ],

        ),

      )

    ],

  ),

);

}

Widget _isLoadingInProgress() {

return _uploadInProgress

    ? CircularProgressIndicator()

    : Row(

        mainAxisSize: MainAxisSize.min,

        children: <Widget>[

          Icon(Icons.file_upload),

          SizedBox(

            width: 5,

          ),

          Text("Upload File"),

        ],

      );

}

}

Thank you

To upload a file you need to do these steps:
“The workflow of creating a file consists of the following steps” section at
https://docs.8base.com/docs/development-tools/sdk/filestack-uploader

1 Like

how to use filestack in flutter can you give me an example?? because give doc I can understand How to do this in fluttter

or if you know any another way to upload a file or image in 8base using flutter please guide me…

Hi @jainsanket784 - unfortunately no one on our team is a flutter/dart developer so we do not have examples that are ready to share with you.

That said, if you’re able to make HTTP requests in flutter you’ll want to make the equivalent to the following POST request after having obtained the needed credentials from the fileUploadInfo query.

curl -X POST \
     --data-binary @FILE_NAME_HERE \
     --header "Content-Type:MIME_TYPE_HERE" 
     "https://www.filestackapi.com/api/store/S3?key=YOUR_API_KEY_HERE&policy=YOUR_POLICY_HERE&signature=YOUR_SIGNATURE_HERE&path=YOUR_PATH_HERE"

hello @sebastian.scholl thank you for your respond.

1 Like