how to upload images in server using flutter and laravel api? - laravel

How to upload images in server using flutter with Laravel API? I tried using getx, its returning null. also I have image_picker and image_cropper package in my pubspec.yaml

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;
}
}

final images = <File>[].obs;
Use this method for picking up images
Future pickImage(ImageSource source) async {
ImagePicker imagePicker = ImagePicker();
XFile pickedFile = await imagePicker.pickImage(source: source, imageQuality: 80);
File imageFile = File(pickedFile.path);
print(imageFile);
if (imageFile != null) {
images.add(imageFile);
} else {
Get.showSnackbar(GetSnackBar(message: "Please select an image file"));
}
}
Use this for uploading images to the server with your specific url.As I have used dio for uploading.You can use http as well.
Future<String> uploadImage(File file) async {
String fileName = file.path.split('/').last;
// you can edit it for your own convenience
var _queryParameters = {
'api_token': 'your token if required',
};
Uri _uri = 'Your base url'
var formData = FormData.fromMap({
"file": await MultipartFile.fromFile(file.path, filename: fileName),
});
var response = await dio.post(_uri, data: formData);
print(response.data);
if (response.data['data'] != false) {
return response.data['data'];
} else {
throw new Exception(response.data['message']);
}
}

This works for me, so maybe others might need it as well.
uploadImage(imageFile) async {
var stream = new http.ByteStream(
DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(
'http://192.168.5.196/ApiFileUploadTest/public/api/uploading-file-api');
var request = new http.MultipartRequest('POST', uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}

Related

how to get the path from image_cropper in flutter?

I want to upload the cropped image in the server but I don't know how to get image path from the cropper. how do I get the path from the cropper. below is my code for cropping and for uploading the cropped image.
this is my code for cropping.
`void _cropImage(filePath) async {
CroppedFile? _croppedFile = await ImageCropper().cropImage(
sourcePath: filePath,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
],
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
IOSUiSettings(
title: 'Cropper',
),
],);
// compressFormat: ImageCompressFormat.jpg);
// cropImagePath.value = croppedFile!.path;
if (_croppedFile != null) {
setState(() {
imageFile = _croppedFile.path;
});
}
}
this is my code for uploading
`uploadImage() async {
var request = http.MultipartRequest(
'POST', Uri.parse('http://hsdgfddf/api/examples/add'));
request.files.add(await http.MultipartFile.fromPath(
'picture', croppedfile!.path));
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
}
You can get the image path when you set it once you received the modified cropped image is received.
Hope this helps.
try this
var request = http.MultipartRequest(
'POST',
Uri.parse("API"),
);
Map<String, String> headers = {"Content-type": "multipart/form-data"};
request.files.add(
http.MultipartFile(
'pic' //picture_index,
selectedImage.readAsBytes().asStream(),
selectedImage.lengthSync(),
filename: croppedImage.path.split('/').last,
),
);
request.headers.addAll(headers);
print("request: " + request.toString());
var res = await request.send();
http.Response response = await http.Response.fromStream(res);

Convert Uint8List image data to ImageGallerySaver saveFile String

how can I convert the Uint8List imagedata of the Screenshot Package to save it with the ImageGallerySaver package saveFile command, which needs a string?
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
setState(() {
_imageFile = image;
});
final result = await ImageGallerySaver.saveFile();
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
I found a solution:
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
String dir =
(await getApplicationDocumentsDirectory()).path;
File file = File("$dir/" +
DateTime.now().millisecondsSinceEpoch.toString() +
".png");
await file.writeAsBytes(image);
setState(() {
_imageFile = image;
});
final result =
await ImageGallerySaver.saveFile(file.path);
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
},
child: Icon(Icons.change_history),
), // Thi

Flutter image_picker "'PickedFile'" can't be assigned to the parameter type 'File'

I'm calling a widget in my code to display the selected image through image-picker plugin; following is my code:
Widget _imagePlaceHolder() {
if (imageSelected == null){
return Text("No File Selected!!");
} else {
Image.file(imageSelected, width: 400, height: 400);
}
}
but I'm getting this error:
The argument type "'PickedFile'" can't be assigned to the parameter type 'File'
on imageSelected under else statement.
I'm picking an image like this from gallery:
Future _openGallery(BuildContext context) async {
var picture = await picker.getImage(source: ImageSource.gallery);
this.setState(() {
imageSelected = picture;
});}
I've defined:
PickedFile imageSelected;
final picker = ImagePicker();
what's going wrong here? Please help..
Image.file() accepts a property of type File class, whereas the ImagePicker().getImage() method returns a type PickedFile.
We have to utilise the getter .path of the returned PickedFile argument and pass that file path to the create a File object as follows:
void _setImage() async {
final picker = ImagePicker();
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
imageFile = File(pickedFile.path);
}
This may be done in one line as follows:
void _setImage() async {
imageFile = File(await ImagePicker().getImage(source: ImageSource.gallery).then((pickedFile) => pickedFile.path));
}
After this, you can use the variable imageFile and pass it inside Image.file() like Image.file(imageFile), or FileImage() like FileImage(imageFile) as required.
For more, see the image_picker documentation on pub.dev
//many time when user import dart.html package than it throw error so keep note that we have to import dart.io
import 'dart.io';
final imagePicker = ImagePicker();
File imageFile;
Future getImage() async {
var image = await imagePicker.getImage(source: ImageSource.camera);
setState(() {
imageFile = File(image.path);
});
}
Change PickedFile imageSelected to File imageSelected and use ImagePicker.pickImage(source: ImageSource.gallery) instead of picker.getImage(source: ImageSource.gallery);
import 'package:image_picker/image_picker.dart';
import 'dart:io';
var image;
void imagem() async {
PickedFile picked = await ImagePicker().getImage(
preferredCameraDevice: CameraDevice.front, source: ImageSource.camera);
setState(() {
image = File(picked.path);
});
}
Or case you need of code full:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class Photos extends StatefulWidget {
#override
_PhotosState createState() => _PhotosState();
}
class _PhotosState extends State<Photos> {
var image;
void imagem() async {
PickedFile picked = await ImagePicker().getImage(
preferredCameraDevice: CameraDevice.front, source: ImageSource.camera);
setState(() {
image = File(picked.path);
});
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Center(
child: Column(
children: [
RaisedButton(
onPressed: imagem,
child: Text("Imagem"),
),
image != null ? Image.file(image) : Text("I")
],
),
));
}
}
Morpheus answer is correct.
Just pass in the PickedFile variable path to File().
Example:
final picker = ImagePicker();
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
imageFile = File(pickedFile.path);
Try converting your imageFile type to PickedImage and return the file in type Casting the imageFile to File, Like:-
// Declaring the variable here
PickedImage imageFile;
And at the time of returning:-
return Image.file(File(imageFile.path),width: 400,height: 400,);
I personally faced this problem, and this solution solved it.
Try this way...
Future pickImageFromGallery() async {
try {
final pickedFile = await picker.pickImage(
source: ImageSource.gallery,
);
setState(() {
widget.imageFile = File(pickedFile!.path);
});
if (pickedFile == null) {
throw Exception('File is not available');
}
} catch (e) {
print(e);
}

Is there an alternative to image_picker_saver dependency

I am working on a code to download image in the device but there are androidx incompatibilities with image_picker_saver dependency.So can anyone suggest an alternative for it?
The complete code-
_saveImage(imageNames) async {
await PermissionHandler()
.checkPermissionStatus(PermissionGroup.storage)
.then((status) async {
if (status == PermissionStatus.denied ||
status == PermissionStatus.disabled ||
status == PermissionStatus.unknown) {
await PermissionHandler().requestPermissions(
[PermissionGroup.storage]).then((status1) async {
if (status1.containsValue(PermissionStatus.granted)) {
await get(imageNames).then((res) async {
await ImagePickerSaver.saveFile(fileData: res.bodyBytes)
.then((str) {
File.fromUri(Uri.file(str));
Fluttertoast.showToast(
msg: "Saved to gallery!",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 15.0);
});
});
}
});
} else if (status == PermissionStatus.granted) {
await get(imageNames).then((res) async {
await ImagePickerSaver.saveFile(fileData: res.bodyBytes).then((str) {
File.fromUri(Uri.file(str));
Fluttertoast.showToast(
msg: "Saved to gallery!",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 15.0);
});
});
}
});
}
You need a package for decoding/encoding algorithms. I suggest this canonicalized package:
https://pub.dev/packages/image
We will use it.
import 'dart:io' as io;
import 'package:http/http.dart' as http;
import 'package:image/image.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
We need bodyBytes for writing file from network image file:
Future<dynamic> downloadImage() async =>
await http.get(url).then((response) => response.bodyBytes);
Get application working directory:
Future<String> createDir() async =>
await getApplicationDocumentsDirectory().then((dir) => dir.path);
First, we will create [Image] type variable, which is provided by image package then we will convert it to a file both decoding and encoding provided by image package again:
Future<io.File> writeFile(String path, var bodyBytes, String fileName) async {
Image image = decodeImage(bodyBytes);
io.File file = io.File(join(path, fileName));
file.writeAsBytesSync(encodePng(image));
return file;
}
So, you created your files, you need to load them, this is the method you need(You can use restored images by [Image.file] widget):
Future<List<io.File>> loadFiles() async {
List<io.File> images = <io.File>[];
final io.Directory dir = await getApplicationDocumentsDirectory();
print('path: ${dir.path}');
for (io.FileSystemEntity f in dir.listSync()) {
if (f is io.File) {
if (f.path.contains('.jpg')) { //any format you want
images.add(f);
}
}
}
return images;
}

How to retreive image data in sqlite database in flutter?

I want to retrieve image data in sqlite. im using below code
var image = await ImagePicker.pickImage(source: imageSource);
List<int> bytes = await image.readAsBytes();
i want to take image and after save it sqlite.if can get and set image from sqlite database ?.
I found the solution in my question.
I'm getting the image from an image_picker and Encode it to BASE64 string value like below
Uint8List _bytesImage;
File _image;
String base64Image;
Future getImage() async {
var image2 = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
List<int> imageBytes = image2.readAsBytesSync();
print(imageBytes);
base64Image = base64Encode(imageBytes);
print('string is');
print(base64Image);
print("You selected gallery image : " + image2.path);
_bytesImage = Base64Decoder().convert(base64Image);
setState(() {
_image=image2;
});
}
after creating an SQLite database dbhelper.dart file to retrieve String values and database model file Image.dart for the get and set the String values.
image.dart
class Image{
int id;
String image;
Employee(this.id, this.image);
Employee.fromMap(Map map) {
id= map[id];
image = map[image];
}
}
dbhelper.dart
class DBHelper {
static Database _db;
Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "test.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
// When creating the db, create the table
await db.execute(
"CREATE TABLE Imagedata(id INTEGER PRIMARY KEY, image TEXT)");
print("Created tables");
}
void saveImage(Imagedata imagedata) async {
var dbClient = await db;
await dbClient.transaction((txn) async {
return await txn.rawInsert(
'INSERT INTO Imagedata(id, image) VALUES(' +
'\'' +
imagedata.id+
'\'' +
',' +
'\'' +
imagedata.image +
'\'' +
')');
});
}
Future<List<Imagedata>> getMyImage() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM Imagedata');
List<Imagedata> images= new List();
for (int i = 0; i < list.length; i++) {
images.add(new Imagedata(list[i]["id"], list[i]["image"]));
}
print(images.length);
return images;
}
Future<int> deleteMyImage(Imagedata imagedata) async {
var dbClient = await db;
int res =
await dbClient.rawDelete('DELETE * FROM Imagedata');
return res;
}
}
last getting String value from the database and Decode String value to the Image file.
Getting image from database
Future<List<Employee>> fetchImageFromDatabase() async {
var dbHelper = DBHelper();
Future<List<Imagedata>> images= dbHelper.getImages();
return images;
}
after Decode string value to the Image file
String DecoImage;
Uint8List _bytesImage;
FutureBuilder<List<Imagedata>>(
future: fetchImageFromDatabase(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
DecoImage=snapshot.data[index].image;
_bytesImage = Base64Decoder().convert(DecoImage);
return new SingleChildScrollView(
child: Container(
child: _bytesImage == null
? new Text('No image value.')
: Image.memory(_bytesImage)
),
);
}
);
}
}
),
i think that is helpful for other flutter,sqlite developers
import 'dart:convert';
import 'dart:typed_data';
    Uint8List bytesImage1;
    bool bolWithImage1 = false;
    try {
      bytesImage1 =
          base64Decode(base64StringFromSql);
      bolWithImage1 = true;
    } catch (err) {}
i.e. if bolWithImage1 is true, the conversion is successful. You can then use image.memory(byteImage1, ......) to show the image in flutter.
You can also save the image as a BLOB (data type: UInt8List). Storing both as Blob (UInt8List) or String(with Base64encoder) in sqflite works. The key was to use MemoryImage instead of Image.memory. Otherwise you would get type 'Image' is not a subtype of type 'ImageProvider ' error.
//First create column in database to store as BLOB.
await db.execute('CREATE TABLE $photoTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colmage BLOB)');
//User imagePicker to get the image
File imageFile = await ImagePicker.pickImage(source: ImageSource.camera, maxHeight: 200, maxWidth: 200, imageQuality: 70);
//Get the file in UInt8List format
Uint8List imageInBytes = imageFile.readAsBytesSync();
//write the bytes to the database as a blob
db.rawUpdate('UPDATE $photoTable SET $colImage = ?, WHERE $colId =?', [imageInBytes, colID]);
//retrieve from database as a Blob of UInt8List
var result = await db.query(photoTable, orderBy: '$colID ASC');
List<Photo> photoList = List<Photo>();
for (int i=0; i<result.length; i++){
photoList.add(Photo.fromMapObject(userMapList[i]));
}
//Map function inside Photo object
Photo.fromMapObject(Map<String, dynamic> map) {
this._id = map['id'];
this._imageFile = map['image'];
}
//Display the image using using MemoryImage (returns ImagePicker Object) instead of Image.memory (returns an Image object).
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundImage: MemoryImage(Photo.image),
backgroundColor: Colors.blueGrey[50],
),
]);

Resources