2
votes

When I try to upload a image to server from Flutter, this error occurres. I don't know how to pass the file to HTTP POSST method, but I took the image and got the file path using the image_picker plugin.

my file path is

:I/flutter ( 9123): File: '/storage/emulated/0/Android/data/com.example.myapp/files/Pictures/2798d03d-2c6b-4f80-8198-94866dfc45962028103221680196242.jpg'

my POST method is like ;

var response = await 

http.post("http://206.189.92.174:4000/API/Posts/Cube_Post_Submit",

    body :
       {
        'attachments' : files ,
       'User_Id' : "5acc5d6e1295332c28f7e205",
       'Cubes_Id' : jsonstring,
       'Post_Text' : "hello",
       'Post_Category' : "Story",
       'Post_Link': ""
       }
    );
   print(response.body);

error will be like this :

[ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception: E/flutter ( 9123): type '_File' is not a subtype of type 'String' in type cast E/flutter ( 9123): #0 Object._as (dart:core/runtime/libobject_patch.dart:74:25) E/flutter ( 9123): #1
CastMap.forEach. (dart:_internal/cast.dart:323:25) E/flutter ( 9123): #2
__InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection/runtime/libcompact_hash.dart:365:8) E/flutter ( 9123): #3 CastMap.forEach (dart:_internal/cast.dart:322:13)

2
Where does http. from http.post come from? Please add the import to your question.Günter Zöchbauer
i just used void upload() async methodArchu Mohan
Where does files come from?Günter Zöchbauer
" just used void upload() async method", sorry, no idea what that means.Günter Zöchbauer
this method is working for without using a image ,,, but when i upload image only this error occursArchu Mohan

2 Answers

1
votes

files in your code looks like plural, but your code doesn't show details.

This is the code to get a single file and this is sent as an array where more than one entry can be added [fileContentBase64] or [file1ContentBase64, file2ContentBase64, file3ContentBase64]

import 'dart:convert';

...
var fileContent = file.readAsBytesSync();
var fileContentBase64 = base64.encode(fileContent); 

var response = await http.post("http://206.189.92.174:4000/API/Posts/Cube_Post_Submit",

    body :
       {
        'attachments' : [fileContentBase64] ,
       'User_Id' : "5acc5d6e1295332c28f7e205",
       'Cubes_Id' : jsonstring,
       'Post_Text' : "hello",
       'Post_Category' : "Story",
       'Post_Link': ""
       }
    );
   print(response.body);
0
votes

You can use the detailed example here that will help you achieve your goals.