How to send Images through Multipart in Flutter - flutter

I want to send three images to my server. I have tried following. There are no errors, no exception but I can't send pictures to the server. Can you help me where I am making the error?
File? image1;
I am picking images from gallery
Future pickImage1() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery,imageQuality: 75);
if (image == null) return;
final imagePermanent = await saveImagePermanently(image.path);
setState(() => image1 = imagePermanent);
} on PlatformException catch (e) {
print('failed to pick image $e');
}
}
It's how I am trying to send images to the server
uploadImage1(File imageFile1,File imageFile2, File imageFile3 ) async {
var postUri = Uri.parse("https://my link");
var request = http.MultipartRequest('POST', postUri);
request.files.add( http.MultipartFile.fromBytes("image1", imageFile1.readAsBytesSync(), filename: "Photo1.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image2", imageFile1.readAsBytesSync(), filename: "Photo2.jpg", ));
request.files.add( http.MultipartFile.fromBytes("image3", imageFile1.readAsBytesSync(), filename: "Photo3.jpg", ));
await request.send().then((response) {
if (response.statusCode == 200)
{
print("Uploaded");
}
else {
print('error');
}
});
}
what I got in my console is
error
Here is the button where I call this function
ElevatedButton(
onPressed: () {
uploadImage1(image1!, image2!, image3!);
print('pressed');
},
child: const Text(' upload '),
),

Do not use both await and then together. Just use await to wait for the execution of the asynchronous function to finish.
final response = await request.send();
if (response.statusCode == 200) {
print("Uploaded");
} else {
print('error');
}

I have a sample code that uploads local images to Pl#nNet, it can be of any help to you, the output for that sample code is like this:
Start fetching...
Fetching done!
{query: {project: all, images: [dc5f659df9a4bcf90fc109830564d821], organs: [leaf],
...
{id: 6411486}}], version: 2022-02-14 (5.1), remainingIdentificationRequests: 197}
Done!

Related

Flutter Android emulator Nexus 6p API 28 and 3rd party API

These 2 methods take a global file that is set later on and send it to OCR Space API to convert and send back a OCR PDF of the file.
The code is running well, and the output value is the OCR correctly, but it is not receiving the the URL of isCreateSearchablePdf (as stated by the OCR Space API)
Is this an issue of emulator? Or is printing value wrong?
OCRSPACEAPI website: https://ocr.space/ocrapi
void fOCR(File file) async {
try {
var uri = Uri.parse('https://api.ocr.space/parse/image?');
var request = new http.MultipartRequest("POST", uri);
request.fields["apikey"] = "myApiKey";
request.fields["language"] = "ara";
request.fields["isOverlayRequired"] = "true";
request.fields["isCreateSearchablePdf"] = "true";
http.MultipartFile multipartFile = await http.MultipartFile.fromPath(
'pdf',
file.path
);
request.files.add(multipartFile);
await request.send().then((response) async {
print("Result: ${response.statusCode}");
print(value);
});
}).catchError((e) {
print(e);
});
} catch(e){
print(e);
}
}
Future selectFile() async {
final result = await FilePicker.platform.pickFiles(allowMultiple: false);
if (result == null) return;
final path = result.files.single.path!;
print(result);
print(File(path));
setState(() => file = File(path));
enabled = true;
}

cannot able to send files with extact format in flutter

I'm currently working in a flutter, I'm trying to send a file to the backend server. But I can send a file but the extension is showing as BIN and the file is not supported.
pick() async {
var img = await ImagePicker().getImage(source: ImageSource.gallery);
image = img;
}
send() async {
// if (imageFile == null) {
// return Get.snackbar("alert", 'Please select image');
// }
try {
String? message = messageController.text;
final url = Uri.parse('http://localhost:8000/integration-test');
//Map<String, String> headers = {'Authorization': 'Bearer $token'};
Uint8List data = await this.image.readAsBytes();
List<int> list = data.cast();
var request = http.MultipartRequest('POST', url)
//..headers.addAll(headers)
..fields['sender'] = "venkat"
..fields['numbers'] = numbers
..fields['message'] = message;
if (image != null) {
request.files.add(http.MultipartFile.fromBytes('file', list,
filename: 'example.jpeg'));
}
var response = await request.send();
//var decoded = await response.stream.bytesToString().then(json.decode);
if (response.statusCode == 200) {
Get.snackbar("alert", 'SUCESS');
} else {
Get.snackbar("alert", 'FAILED');
}
} catch (e) {
Get.snackbar('alert', 'Image failed: $e');
}
}
and help to set the file name dynamically.
when i done it with ajax and jquery it works file i need the exact result like this
let formData = new FormData();
let file = $('#1file')[0].files[0];
const sender=c;
const message = $('.i-message').val();
const datepick=$("#i-datetimepicker").val();
formData.append('sender',c);
formData.append('numbers',JSON.stringify(irecepient));
formData.append('message',message);
if(file){
formData.append('file',file);
}
if(datepick){
formData.append('date',datepick);
}
$.ajax({
type: "POST",
url: "http://localhost:8000/integration-test",
//enctype: 'multipart/form-data',
contentType:false,
processData:false,
data: formData,
success: function (data) {
if(data !=0){
$('.logs').append($('<li>').text("task processing"));
}else{
$('.logs').append($('<li>').text("task failed"));
}
}
});
});
this works good and i expect the above flutter code to do this

Upload image to server flutter (Image picker)

I want to upload an image to server
I'm using the Image Picker plugin to pick image
this code work without any exception on samsung tab
but Catch error on xiaomi phone.
the onImageButtonPressed run in all devices.
Future<void> onImageButtonPressed({
BuildContext? context,
}) async {
try {
final XFile? pickedFile =
await picker.pickImage(source: ImageSource.camera);
if (pickedFile != null) {
imageFileList!.add(pickedFile);
logger.i('done , image picked');
File image = File(pickedFile.path);
logger.i(image); // on xiaomi and samsung log the same result "File: '/data/user/0/com.grand.technology.driver/cache/8227d4f4-df70-441d-9677-b95b64b1bf323122241454085685040.jpg'"
await uploadOrderPic(order.id.toString(), image);
}
update();
} catch (e) {
pickImageError = e;
logger.e(e);
update();
}
}
but the exception happen here
uploadOrderPic(String id, File image) async {
uploading.value = true;
var response = await OrderApi()
.uploadOrderPic(orderID: id, image: image)
.then((value) {
logger.i(value.data); //samsung tab log Instance of 'UploadedImage' but xiaomi phone catch error
uploading.value = false;
var uploadedImage = (value.data) as UploadedImage;
imageURLsList.add(uploadedImage.url!);
}).catchError((error) {
Get.snackbar('Failed', 'Uploading Image Failed',
backgroundColor: redColor);
logger.e(error); // type 'Null' is not a subtype of type 'UploadedImage' in type cast
});
try {
} on TimeoutException {
Get.snackbar(
'Connection Error', 'Check Your Internet Connection Please!');
} catch (e) {
logger.e(e);
}
}
this code upload image to server
Future<ApiResponse> uploadOrderPic(
{required String orderID,
required File image}) async {
ApiResponse apiResponse = ApiResponse();
var token = await getToken();
try {
var request = http.MultipartRequest("POST", Uri.parse(uploadPicUrl));
request.files.add(await http.MultipartFile.fromPath('image', image.path));
request.fields['id'] = orderID;
request.headers[HttpHeaders.authorizationHeader] = 'Bearer $token';
var response =
await request.send().then((value) => http.Response.fromStream(value));
apiResponse.data =
UploadedImage.fromJson(jsonDecode(response.body)['data']);
} catch (e) {
logger.e(e);
apiResponse.error = serverError;
}
return apiResponse;
}

Image upload using post method in Flutter

I have to upload image from gallery to server using provider in Flutter.
Here is the file picker
_loadPicker(ImageSource source) async {
File picked = await ImagePicker.pickImage(source: ImageSource.gallery);
print(picked);
if (picked != null) {
final response = await Provider.of<ProfilePictureUpdate>(context, listen:
false).profilePicUpdate(picked);
if (response["status"] ) {
Fluttertoast.showToast(msg: response["title"]);
}
else {
Fluttertoast.showToast(msg: response["title"]);
}
}
}
And here is the post method
Future<Map<String, dynamic>> profilePicUpdate(picked) async {
try {
final response = await ApiRequest.send(route: "profile/update/picture", method: "POST",
body: {
" photo_url" : picked,
});
if (response.statusCode == 200 ) {
return {
"status": true,
"title" : response["title"]
};
}
}
If you want sent image to you have to use formData( multi part) in 'Dio' similar
web (enctype). In http, you can also use multipart.
Must remember u use image is always not same, here use this field when server side params name same.
class ImageRepository {
Future<dynamic> uploadImage(filepath) async {
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(filepath,
filename: filepath.split('/').last)
});
var response = await Dio().post(
url,
data: formData),
);
print(response.data);
if (response.statusCode == 200) {
return 'Image Upload';
} else {
throw Exception 'Problem occour';
}
}

How to upload image to server API with Flutter [duplicate]

This question already has an answer here:
Upload image with http.post and registration form in Flutter?
(1 answer)
Closed 3 years ago.
I am new to Flutter development. My problem is that I try to upload the image but I keep getting failed request.
This piece of code is where I connect it with a server API which will receive the image file from Flutter. String attachment which consist of the image path that is passed from createIncident function located at another page.
Future<IncidentCreateResponse> createIncident( String requesterName, String requesterEmail,
String requesterMobile, String attachment, String title,
String tags, String body, String teamId,
String address ) async {
IncidentCreateResponse incidentCreateResponse;
var url = GlobalConfig.API_BASE_HANDESK + GlobalConfig.API_INCIDENT_CREATE_TICKETS;
var token = Auth().loginSession.accessToken;
var postBody = new Map<String, dynamic>();
postBody["requester_name"] = requesterName;
postBody["requester_email"] = requesterEmail;
postBody["requester_mobile_no"] = requesterMobile;
postBody["attachment"] = attachment;
postBody["title"] = title;
postBody["tags"] = tags;
postBody["body"] = body;
postBody["teamId"] = teamId;
postBody["address"] = address;
// Await the http get response, then decode the json-formatted responce.
var response = await http.post(
url,
body: postBody,
headers: {
'X-APP-ID': GlobalConfig.APP_ID,
"Accept": "application/json; charset=UTF-8",
// "Content-Type": "application/x-www-form-urlencoded",
HttpHeaders.authorizationHeader: 'Bearer $token',
'token': GlobalConfig.API_INCIDENT_REPORT_TOKEN
}
);
if ((response.statusCode == 200) || (response.statusCode == 201)) {
print(response.body);
var data = json.decode(response.body);
incidentCreateResponse = IncidentCreateResponse.fromJson(data['data']);
} else {
print("createIncident failed with status: ${response.statusCode}.");
incidentCreateResponse = null;
}
return incidentCreateResponse;
}
This is the code snippet where I get the image path from the selected image from the gallery
Future getImageFromGallery(BuildContext context) async {
var picture = await ImagePicker.pickImage(source: ImageSource.gallery);
setState((){
_imageFile = picture;
attachment = basename(_imageFile.path);
});
Navigator.of(context).pop();
}
This is the code where I passed the attachment string to the HTTP Response
this.incidentService.createIncident(
Auth().loginSession.name,
Auth().loginSession.email,
Auth().loginSession.mobile_no,
this.attachment,
this._titleController.text,
this._tags,
this._contentController.text,
this._teamId,
this._addressController.text
).then((IncidentCreateResponse res) {
if (res != null) {
print('Ticket Id: ' + res.id);
// Navigator.pop(context);
this._successSubmittionDialog(context);
} else {
this._errorSubmittionDialog(context);
}
}
You can upload image using multipart or base64 Encode.
For uploading image using multipart Visit the Official documentation
For uploading image using base64 Encode you can checkout the Tutorial Here
I suggest using multipart image upload as it is even reliable when your image or files are larger in size.
Hope this could help you,
create a function to upload your image after picking or clicking an image like,
Future<ResponseModel> uploadPhoto(
String _token,
File _image,
String _path,
) async {
Dio dio = new Dio();
FormData _formdata = new FormData();
_formdata.add("photo", new UploadFileInfo(_image, _path));
final response = await dio.post(
baseUrl + '/image/upload',
data: _formdata,
options: Options(
method: 'POST',
headers: {
authTokenHeader: _token,
},
responseType: ResponseType.json,
),
);
if (response.statusCode == 200 || response.statusCode == 500) {
return ResponseModel.fromJson(json.decode(response.toString()));
} else {
throw Exception('Failed to upload!');
}
}
then you can use use uploadImage,
uploadImage(_token, _image,_image.uri.toFilePath()).then((ResponseModel response) {
//do something with the response
});
I have used Dio for the task, you can find more detail about dio here
Add this to your package's pubspec.yaml file:
dependencies:
dio: ^3.0.5
Then import it in your Dart code, you can use:
import 'package:dio/dio.dart';
To upload image using multipart API use this code ie
Add this library dio in your project in pubspec.yaml file
dio: ^3.0.5
and import this in your class
import 'package:dio/dio.dart';
Declare this variable in your class like State<CustomClass>
static var uri = "BASE_URL_HERE";
static BaseOptions options = BaseOptions(
baseUrl: uri,
responseType: ResponseType.plain,
connectTimeout: 30000,
receiveTimeout: 30000,
validateStatus: (code) {
if (code >= 200) {
return true;
}
});
static Dio dio = Dio(options);
then use this method to upload file
Future<dynamic> _uploadFile() async {
try {
Options options = Options(
//contentType: ContentType.parse('application/json'), // only for json type api
);
var directory = await getExternalStorageDirectory(); // directory path
final path = await directory.path; // path of the directory
Response response = await dio.post('/update_profile',
data: FormData.from({
"param_key": "value",
"param2_key": "value",
"param3_key": "value",
"profile_pic_param_key": UploadFileInfo(File("$path/pic.jpg"), "pic.jpg"),
}),
options: options);
setState(() {
isLoading = false;
});
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = json.decode(response.data);
return responseJson;
} else if (response.statusCode == 401) {
print(' response code 401');
throw Exception("Incorrect Email/Password");
} else
throw Exception('Authentication Error');
} on DioError catch (exception) {
if (exception == null ||
exception.toString().contains('SocketException')) {
throw Exception("Network Error");
} else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
exception.type == DioErrorType.CONNECT_TIMEOUT) {
throw Exception(
"Could'nt connect, please ensure you have a stable network.");
} else {
return null;
}
}
}