How to send image file with POST request in Flutter - flutter

I need to pass an image file that I have taken from the camera, directly as param with a POST method in Flutter.

You can use MultipartFile from the http library
var request = http.MultipartRequest('POST', Uri.parse('YourUrl'));
request.files.add(
http.MultipartFile.fromBytes(
'YourField',
File('YourFilename').readAsBytesSync(),
filename: 'YourFilename'
)
);
var res = await request.send();

Related

Uploading a file to server using http MultiPartRequest

Hello to everyone i hope you all good.
Im trying to upload a image to a server im using this:
But it dosent work. So please help me, i would really appreciate it.
Future<int> uploadFile(imageFile) async {
try {
var request = http.MultipartRequest(
'POST',
Uri.parse('http://10.0.2.2:8000/objects/'),
);
Map<String, String> headers = {"Content-type": "multipart/form-data"};
request.files.add(
http.MultipartFile(
'file',
imageFile.readAsBytes().asStream(),
imageFile.lengthSync(),
contentType: MediaType(
'image',
'jpeg',
),
),
);
request.headers.addAll(headers);
request.fields.addAll({
"app_label": "files",
"app_model": "file",
});
print("request: " + request.toString());
var res = await request.send();
print("This is response:" + res.toString());
return res.statusCode;
} catch (err) {
print(err);
return 502;
}
}
Response from the server and vscode:
https://ibb.co/2SMTBxJ
You can check the project here:
https://github.com/bRUNS123/hydra
Also if someone know how to put the image without crop like the "finished" file.
I the app you can take an image from the gallery or camera, then you have a preview and you can send or save to the gallery. But i created an option to avoid the crop image, but when i try to pass the information to not crop, nothing happen.
Also i wanna know if i can put all my void functions in a separated file.
Hope you have a great day!!

How to Overwrite or Update Cache files in Flutter while using Path Provider

Below Code i have created for local caching using path provider
String fileName="pathString.json";
var dir=await getTemporaryDirectory();
File file=File(dir.path+"/"+fileName);
if(!file.existsSync()) {
final http.Response response = await http.get(
Uri.parse("https://*************.herokuapp.com/*********"));
file.writeAsStringSync(
response.body, flush: true, mode: FileMode.write);
final data = file.readAsStringSync();
responseData = json.decode(data);
}else{
final data = file.readAsStringSync();
responseData = json.decode(data);
final http.Response response = await http.get(
Uri.parse("https://**************.herokuapp.com/*********"));
file.writeAsStringSync(
response.body, flush: true, mode: FileMode.write);
}
for first time, File can be Created. But For Second time.. Once File is created, and API fetches latest response with updated data, Cache file not get overwritten.
It would be great, if anyone can help on this..
Thanks in Advance.
i suppose that in your case happening something similar, to my situation:
For flutter Image class i found that, it use ImageCache for caching images, so when you rewrite Image and save it in filesystem, image will look the same until you restart app or invalidate cache.
Code that i wrote for cache invalidation for image:
import 'dart:io';
import 'package:flutter/material.dart';
// imgBytes - raw image bytes here empty just for example
// location - path to image in fs
updateImage(Uint8List imgBytes) async {
var file = File(location);
await file.writeAsBytes(imgBytes, mode: FileMode.write); // rewrite file content
var img = Image.file(file); // create Image class
img.image.evict(); // invalidate cache key for this image
}

Flutter: Convert Base64 String image url to File and use it in FileImage or related widgets

I've tried this way, and use it in FileImage but haven't found a rally point
Uint8List bytes = base64.decode(imageBase64);
File file = File.fromRawPath(bytes);
imageBase64 is the image url that has been encode.
The point of this thing is, i want to use it in FileImage or another widget image file but i don't want this image is saved to device and upload this file to the attachments file Rest API
can anyone help me.
If what you want to do once you have the bytes is to show the image, then you can use Image.memory.
var imageWidget = Image.memory(bytes);
OTOH If you're trying to upload the image, you don't need to convert it into file. You can use bytes directly assuming you can't upload it using base64 enconding. Package http
import 'package:http/http.dart';
...
//create multipart using filepath, string or bytes
MultipartFile multipartFile = MultipartFile.fromBytes(
'file',
byteData,
filename: fileName,
);
//add multipart to request
request.files.add(multipartFile);
var response = await request.send();
If you have an UintList8 you can use MemoryImage(bytes).
Uint8List bytes = base64.decode(imageBase64);
Image(image: MemoryImage(bytes));

saving image(url format ) from api in sqlite local datbase but don't know how

i have api which have images in url ,i want to save that image in sqlite local database for cart page purpose in my flutter app ,i did some search on google by that i found to convert in image to base 64 which will convert the image to string but that like in png or jpeg or that format but i have my images from api url. i dn't know how to do it any help will be appreciated
"images": [
"https://west-1.amazonaws.com/images/full/5bc9839886fc106413b9407f42ed776b9b7bd9.jpg",
],
i have images like this
Add the http package:
http: ^0.12.0+2
Imports:
import 'package:http/http.dart' as http;
import 'dart:convert';
Download the image and base64 encode:
// Substitute your image URL
String uri = 'https://pub.dev/static/img/pub-dev-logo-2x.png?hash=umitaheu8hl7gd3mineshk2koqfngugi';
http.Request request = http.Request("GET", Uri.parse(uri));
http.StreamedResponse streamedResponse = await request.send();
http.Response response = await http.Response.fromStream(streamedResponse);
if(response.statusCode != 200) {
throw Exception("Couldn't get data becuase of ${response.statusCode}");
}
String data = base64.encode(response.bodyBytes);

How to post asset image to server using MultipartFile in flutter

I am using MultipartFile to send my image file to server. I know that when I use ImagePicker
File ImageFile;
_openCamera() async {
var picture = await ImagePicker.pickImage(source: ImageSource.camera);
this.setState(() {
imageFile = picture;
});
}
then use MultipartFile like this
request.files.add(http.MultipartFile.fromBytes('img', ImageFile.readAsBytesSync(), filename: 'photo.jpg'));
But my problem is I want my image is from my assets like from here Image.asset('images/photo1.png');. I have error
A value of type 'Image' can't be assigned to a variable of type 'File'.
Try changing the type of the variable, or casting the right-hand type to 'File'.
So, my question is how I can send my image using MultipartFile method?
First, obtain the asset as list of bytes:
var bytes = (await rootBundle.load('images/photo1.png')).buffer.asUint8List();
Then use that in the MultipartFile named constructor:
var mpFile = http.MultipartFile.fromBytes('img', bytes, filename: 'photo.jpg');