How to use image string in Image widget

When I am uploading a file to the server, I am getting a String in response. How can I use That String to set that image at the image widget?

I am pasting here code snippet

_uploadImage() async {
var file = await ImagePicker.pickImage(source: ImageSource.gallery);
var filename = file.path;
var request = http.MultipartRequest(‘POST’, Uri.parse(url));
request.files.add(await http.MultipartFile.fromPath(‘myFile’, filename));
StreamedResponse res = await request.send();
var response = await http.Response.fromStream(res);
print(“response123 : ${response.body}”);
var j = json.decode(response.body);
print(“picture is ${j[‘filename’]}”);
// final decodedBytes = base64Decode(j[‘filename’]);
}

What is it that you are getting in response? Is it the image url? If it is the image link then you can simply display the image using Image.network(${response.body});.

Else if it is a binary you can try new Image.memory(${response.body}).

Let us know if any of these work :slight_smile:

1 Like

Hi @prabhu_nath this are the methods you can use in Flutter for Images:

  1. Image.asset - To display image from assets bundle
  2. Image.file - To display image from a file
  3. Image.memory - To display image from Uint8List
  4. Image.network - To display image from a URL

Loading from a base64 is going to be a little bit more intensive that from a URL, so if you get a simple URL in j[filename] I would use the Image.network(j['filename']) Widget.

But if you want to use base64 the you can use the Image.memory() method with a decoding the base64 to bytes:

Uint8List bytes = BASE64.decode(_base64);
Image.memory(bytes);

BTW, I would recommend you use Types in all you variables and create a class for the result of you call to the database. It may be a little bit more work upfront, but you end up with far less errors, a more readable and scalable code and in the end develop faster.

So your code would look like:

_uploadImage() async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
String filename = file.path;
var request = http.MultipartRequest(‘POST’, Uri.parse(url));
request.files.add(await http.MultipartFile.fromPath(‘myFile’, filename));
StreamedResponse res = await request.send();
var response = await http.Response.fromStream(res);
print(“response123 : ${response.body}”);
ImgaeFromDB j = ImageFromDB.fromJson(json.decode(response.body));
print(“picture is ${j.fileName}”);
Uint8List  decodedBytes = BASE64.decode(j.fileName);
}

class ImageFromDB{
final Sting fileName;

ImageFromDB ({@required this.fileName});

ImageFromDB.fromJson(Map data){
return ImageFromDB (
fileName: data['filename'] ?? '',
);
}
1 Like

It’s not working. I am pasting below what I am getting in response.body

{fieldname: myFile, originalname: image_picker7878715052010262757.jpg, encoding: 7bit, mimetype: application/octet-stream, destination: ./uploads/, filename: 7137721a09872c34280a07bdf40d79df, path: uploads/7137721a09872c34280a07bdf40d79df, size: 6368}

I tried these but getting error: E/flutter (18305): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type ‘_InternalLinkedHashMap<String, dynamic>’ is not a subtype of type ‘String’

I am getting this response from the server after uploaded my file

{fieldname: myFile, originalname: image_picker1848282020404709832.jpg, encoding: 7bit, mimetype: application/octet-stream, destination: ./uploads/, filename: c2a05ec1a68edfc98e87921cbaf1597a, path: uploads/c2a05ec1a68edfc98e87921cbaf1597a, size: 835665}

Hi @prabhu_nath it looks like you are trying to use a Map in the place of a String variable.

Please paste your code so we can help a bit more.

A part from that it is not very clear where the URL of the image in the server is coming from. There are no fields in the response you shared with a full URL.

What are you using as a server? Do you need to build the URL from the fields in the response?

I am using multer in nodeJs server, Yes I need image URL from the fields in the response.

But do you need to build it? Because you are not getting a full path. When you call filename that is not a full URL. You need to build it with all the fields you’ve received. That must be in the multer docs.

And please paste some code to find other errors.

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const multer = require(‘multer’);
const upload = multer({ dest: ‘./uploads/’ });
const hbs = require(‘hbs’);
var path = require(‘path’);
var fs = require(‘fs’);
const logger = require(‘morgan’);

const progress = require(‘progress-stream’);
var str = progress({ time: 100 });

// Define port for app to listen on
const port = process.env.PORT || 8080;

/* ==================================================== /
/
===== Section 2: Configure express middlewares ===== /
/
==================================================== */

const app = express();
app.use(bodyParser()); // to use bodyParser (for text/number data transfer between clientg and server)
app.set(‘view engine’, ‘hbs’); // setting hbs as the view engine
// app.use(express.static(__dirname + ‘/public’)); // making ./public as the static directory
app.set(‘views’, __dirname + ‘/views’); // making ./views as the views directory
app.use(logger(‘dev’)); // Creating a logger (using morgan)
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, ‘public’)));
var dir = path.join(__dirname, ‘uploads’);

/* ==================================== /
/
===== Section 3: Making Routes ===== /
/
==================================== */

// GET / route for serving index.html file
app.get(’/’, (req, res) => {
res.render(‘index.hbs’);

});
app.get(’/upload’, (req, res) => {
res.redirect(’/’);
})

// POST /upload for file upload
/* ===== Make sure that file name matches the name attribute in your html ===== */
app.post(’/upload’, upload.single(‘myFile’), (req, res) => {
// str.on(‘progress’, function(progress) { });

if (req.file) {
    console.log('Uploading file...', req.files, req.file);
    var filename = req.file.filename;
    var uploadStatus = 'File Uploaded Successfully';
} else {
    console.log('No File Uploaded');
    var filename = 'FILE NOT UPLOADED';
    var uploadStatus = 'File Upload Failed';
}

/* ===== Add the function to save filename to database ===== */
res.send({ status: uploadStatus, filename: req.file });

// res.render('index.hbs',{ status: uploadStatus, filename: `Name Of File: ${filename}` });

});

// GET /temp to render temp.hbs, for dev purposes
app.get(’/temp’, (req, res) => {
res.render(‘temp.hbs’);
});

// To make the server live
app.listen(port, () => {
console.log(App is live on port ${port});
});