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

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

Related

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

Is there something wrong with the way [Flutter Web] sends a request POST message to the API server?

The open api request I'm trying to use requires an image binary value with content-type of multipart/form-data format.
I know you can't use dart:io in flutter web. I tried to upload an image in multipart/form-data format to the api server in flutter web while looking at several posts.
However, only a message appeared stating that the image could not be recognized.
This is the last thing I tried to create multipart types in flutter web.
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
PlatformFile? objFile;
pickImage() async {
var result = await FilePicker.platform.pickFiles(
withReadStream: true,
);
setState(() {
objFile = result!.files.single;
});
uploadImage();
}
uploadImage() async {
FormData formData = FormData.fromMap({'image' : MultipartFile(test!, objFile!.size, filename: objFile!.name)});
Dio dio = new Dio();
var response = await dio.post('API url', data: formData);
}
I additionally used Multipart.form Bytes from http , Multipart.form Bytes from dio . But the result was the same.
The value checked by the request body through the postman interceptor.
content-type=multipart/form-data;bounary=--dio-boundary-1105759322
----dio-boundary-1105759322
content-disposition: form-data; name="image"; filename="test.jpeg"
content-type: application/octet-stream
ÿØÿÛC
%# , #&')*)-0-(0%()(ÿÛC
(((((((((((((((((((((((((((((((((((((((((((((((((((ÿÀŽv"ÿÄÿÄC!1AQaq"‘2¡±#BÁÑR3CðñSbr’á‚Â$&4c“ÿÄÿÄ&!1A2Q"a3BRÿÚ?ù× „É<$/cŸt8D`aú¦Ä#bálŒZVM„ٔʓTL›eOò¢“
èKÇ(p¢‰¥C’ÄÙ‚Ñx²Ù1Jcœ)B›¢$ ¢‚&
‚7› ˜Žp”{&ÊÀÁAî¤Æ
‚nÈ CØÃêOýÒ›§á$sÊ‚r¡ìLÂ…;"éMI½î«gæV<æ6οÙ%_ƒY®}7Òû€¯MŒ&g¹å|µ£ëÐúc\tÚƵƈúÕ]#kQ‹D/Ÿú·cu9«Hà/¢lÚ–êè·¼&Þt
¯H‚&ɶìÛà®iƒh²SöãÔTs[l›/?[s(’˜¨o€¤Û‹*¥AÖ”ðbUgYR’!äJ!M‹™‹«›î©aÉ*ᕨ4p SÉ…¤)‰ì§=‘âJ» oÙGDRåÌy0—²û r ò€·²?Te8±KSTR8ŹDAååþ7)Oˆk)õ²Qk#Ù€Œ ?DÜû&Ä›„ÍÅ”lQjð¡NÑ%HTWP˜²wýÒc(Ÿð¤ð¢S<*6º>ÊaCœ „Ù0
^J(ª%¢ƒFPm‘^u4^èM‘åL…##•0Qÿ ºi…32§ÙC•D¿&Èw’ˆº‘Ü"…”<&ýРwP {p ¸DCd¼&ÿ©#¨ˆ› La~¨p¦„)’÷‚ˆº²æÒ›ªĘ̀Šaá€0‹n <ò¦M“YM„ L«=ÕnæÊlªŽÂƒóc„m‚—È™Uó ªºäªÛ•F†\…}7?¨ªZL`*£è¾ŽÝÌ1¤ÜBúk6­
---------------------------SKIP------------------------------
PTiMÂ!¢(èÊ€YÊÂœ"ÑÂ_T<Ñ5îPp™ð ¨„ôOˤ?¢z\ÂÚ¡½ÐiÊc쨟ÝHŸ¢“3ÝA˜( ‘ÊH›(l€Å¼)Ä‘rEÈ[€‹¬”¼x
W7q?ΣHt®“§¤y\½Ìÿ:ÿÍtÖ§T°AÊÕ\ËZVƒÔPha30%1*¶›Ž!7è¥|f›„îÕQ±„9N6åW,¨^Ù8PHN./Ê€îª2ß*{(l¡™šOU¢Ôå3œ*ꜨŠ‹“3¼$«B*ÌŒS„+EÒ‘Ý VHpV±`²³ó€µgܪ‚#“Ü)À!NPCƒÝIÅԛ–”xý”²™# ?U‚‹n€å!Œ¦&é*ƒ™¨wÄÖØY¢>«}&ü¢×\Ý?ó*9ç%Òº˜#çò H€¥&ꃒ¤(
‚0O8##EÎéÊœ#TÕr‚ºT¹ÈÔ7T“2¢ƒœbÅsuOî¶Ô0>‹ŸT|Gô•Óa®ïšÔÇe¤T
he<,¨[ü¶[…·M#ZOˆjtˤÝE© QÿÙ
----dio-boundary-1105759322--
When I use the MultipartFile.fromFile method used in flutter ios, I got the response normally. So I'm pretty sure there must be some mistake or misinformation in the flutter web setup.
Thanks in advance!
this is how I managed to upload an image to Laravel backend using Flutter Web
import 'dart:io';
import 'package:dio/dio.dart' as dio;
import 'package:file_picker/file_picker.dart';
Future pickupUserImage2() async {
PlatformFile? objFile;
var picked = await FilePicker.platform.pickFiles();
objFile = picked!.files.single;
String? apiUrl = Get.find<MainController>().apiUrl;
String url = '';
if (apiUrl != null) url = apiUrl + 'images';
List<int> list;
list = List<int>.from(objFile.bytes!);
dio.FormData formData = dio.FormData.fromMap({'file': dio.MultipartFile.fromBytes(list, filename: objFile.name)});
DioNetworking _dio = new DioNetworking();
dynamic result = await _dio.postData(
url,
formData,
contentType: 'multipart/form-data',
);
if (result['status'] == true) {
showToast(result['message']);
return ImageModel.Image.fromJson(result['data']);
}
}
I added a file using MultipartFile.fromBytes which has the first parameter as List which I created from this method "List.from(objFile.bytes!);"
Notes :
ImageModel.Image is a model I created to handle the image result
DioNetworking is a class that perform dio requests , I just created it to do the
authentication stuff
import 'package:dio/dio.dart';
class DioNetworking {
Dio _dio = new Dio();
Future postData(
String url,
dynamic data, {
String? contentType,
}) async {
try {
Response response = await _dio.post(url,
data: data,
options: Options(headers: {
'content-type': contentType != null ? contentType : 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer ${token ?? ''}'
// other headers
}));
if (response.statusCode == 200) {
dynamic data = response.data;
return data;
} else {
print(response.statusCode);
}
} on DioError catch (e) {
print(e);
if (e.type == DioErrorType.connectTimeout) {
return {'status': 'Connect Timed Out'};
}
if (e.type == DioErrorType.receiveTimeout) {
return {'status': 'Receive Timed Out'};
}
if (e.type == DioErrorType.response) {
print(e.response!.data);
print(e.response!.headers);
}
}
}
}

Image Upload in Flutter Using Http post method

I'm new in this Framework and I want to Upload the Image along with the User name id and wmail and phone,
but Unable to to that I'm getting error
this is the Image get image function
File _image;
final picker = ImagePicker();
Future getImage() async {
pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Here i have written the Code for Upkoadung How to do Please help me with that
Future updateUserApiCall(
String name, String email, String mobile, File profile) async {
String token;
var userId;
SharedPreferences storage = await SharedPreferences.getInstance();
token = storage.getString("apiToken");
userId = storage.getInt("id");
String url = "https://www.example.com/api/updateprofile";
final response = await http.post(
url + "?page=" + "",
body: json.encode({
'user_id': userId,
'email': email,
'name': name,
'phone': mobile,
'image': profile,
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + token,
},
);
if (response.statusCode == 200) {
print(response.body);
return UpdateProfileResponseModel.fromJson(
json.decode(response.body),
);
} else if (response.statusCode == 400) {
print(response.body);
return ErrorResponseModel.fromJson(
json.decode(response.body),
);
} else if (response.statusCode == 422) {
print(response.body);
return ValidationErrorResponseModel.fromJson(
json.decode(response.body),
);
} else {
print(response);
throw Exception('Failed to load data!');
}
}
}
As far as I know you can not pass image data using just http.post method. You have to use Multipart Request. I have also faced similar problem and asked a similar question in StackOverFlow. Please check the link below:
uploading image using file_picker flutter to a nodejs server
My use case was updating image of an user, I have used the following code to send image to a node server.
Future<bool> updateImage(File imageFile, AuthModel authModel) async{
final String _accessToken = 'abc';
final String url =
'https://justyourserverURL.com/update';
print("auth : " + _accessToken);
var request = http.MultipartRequest('POST', Uri.parse(url));
request.headers['Authorization'] = _accessToken;
// request.fields['id'] = '104';
// request.fields['firstName'] = authModel.data.firstName;
// request.fields['lastName'] = authModel.data.lastName;
// request.fields['surname'] = authModel.data.surname;
request.files.add(await http.MultipartFile.fromPath('file', imageFile.path));
var res = await request.send();
final respStr = await res.stream.bytesToString();
print('responseBody: ' + respStr);
if(res.statusCode==200){
setCurrentUser(respStr);
currentUser = authModelFromJson(respStr);
return true;
} else {
print(respStr);
print('Failed');
return false;
}
}
To pass username or id just pass data using request.fields['user_id'] = userId.

flutter dio upload files [pdf/ docs]

I am trying to upload files using dio package in my flutter application. I am sending my files through formdata. Here is my implementation:
Future<FormData> formData1() async {
return FormData.fromMap({
"title": "from app2",
"description": "app upload test",
"files": [
for (var i = 0; i < pathNames.length; i++)
await MultipartFile.fromFile(pathNames[i],
filename: fileNames[i])
]
});
}
Here is how I am sending my files.
_sendToServer() async {
Dio dio = Dio(
BaseOptions(
contentType: 'multipart/form-data',
headers: {
"Authorization": "$token",
},
),
);
dio.interceptors.add(
LogInterceptor(requestBody: true, request: true, responseBody: true));
FormData formData = await formData1();
try {
var response = await dio.post("http://url/api/upload",
data: formData, onSendProgress: (int send, int total) {
print((send / total) * 100);
});
print(response);
} on DioError catch (e) {
if (e.response != null) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
} else {
print(e.request.headers);
print(e.message);
}
}
}
The other fields in formdata are sent to the server but not the multipartfile. When I try and do the same from postman form-data, it uploads correctly. Am I doing something wrong here?
If you want to upload the file you can convert multipart array before calling API function because even if you put await in form data dio response will not wait for formdata object or you can use MultipartFile.fromFileSync() to get rid of await.
Let me show you in a simple way using my example. try to understand.
Multipart conversion
List multipartArray = [];
for (var i = 0; i < pathNames.length; i++){
multipartArray.add(MultipartFile.fromFileSync(pathNames[i], filename:
basename(pathNames[i])));
}
Api side
static Future<Response> createPostApi(multipartArray) async {
var uri = Uri.parse('http://your_base_url/post');
return await Dio()
.post('$uri',
data: FormData.fromMap({
"title": "from app2",
"description": "app upload test",
"files": multipartArray
}))
.catchError((e) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
});
}
Here is my code where I used file_picker flutter library and MediaType('application', 'pdf') to ensure that the content passed to the API was indeed a .pdf file.
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
static Future<dynamic> uploadfile(int userid, File file, String token) async {
var fileName = file.path.split('/').last;
print(fileName);
var formData = FormData.fromMap({
'title': 'Upload Dokumen',
'uploaded_file': await MultipartFile.fromFile(file.path,
filename: fileName, contentType: MediaType('application', 'pdf')),
"type": "application/pdf"
});
var response = await Dio().post('${urlapi}request/',
options: Options(
contentType: 'multipart/form-data',
headers: {HttpHeaders.authorizationHeader: 'Token $token'}),
data: formData);
print(response);
return response;
}
The file picker:
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path ??'file.pdf');
BlocProvider.of<UploadCubit>(context)
.uploadFile(statelogin.user.id, file,
statelogin.user.token);
}
Change formdata with following rest is fine
import 'package:path/path.dart' as pathManager;
import 'package:mime/mime.dart' as mimeManager;
FormData formdata = FormData();
formdata.add(
"files",
[UploadFileInfo(img, pathManager.basename(img.path),
contentType:
ContentType.parse(mimeManager.lookupMimeType(img.path)))]);
// here attachmentFile is File instance, which is set by File Picker
Map<String, dynamic> _documentFormData = {};
if (attachmentFile != null) {
_documentFormData['document_file'] = MultipartFile.fromFileSync(attachmentFile.path);
}
FormData formData = FormData.fromMap(_documentFormData);
try {
var response = await dio.post("http://url/api/upload",
data: formData, onSendProgress: (int send, int total) {
print((send / total) * 100);
});
print(response);
} on DioError catch (e) {
if (e.response != null) {
print(e.response.data);
print(e.response.headers);
print(e.response.request);
} else {
print(e.request.headers);
print(e.message);
}
}
Here you can use MultipartRequest class without using any of library to upload any kind of files using restAPI.
void uploadFile(File file) async {
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
MultipartFile multipartFile = await http.MultipartFile.fromPath(
'idDocumentOne_1',
file.path
);
// add file to multipart
request.files.add(multipartFile);
// send request to upload file
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
I used file picker to pick file. Here is the codes for pick file.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'],
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}
here file_picker flutter library.

How to upload images and file to a server in Flutter?

I use a web service for image processing , it works well in Postman:
Now I want to make http request in flutter with Dart:
import 'package:http/http.dart' as http;
static ocr(File image) async {
var url = '${API_URL}ocr';
var bytes = image.readAsBytesSync();
var response = await http.post(
url,
headers:{ "Content-Type":"multipart/form-data" } ,
body: { "lang":"fas" , "image":bytes},
encoding: Encoding.getByName("utf-8")
);
return response.body;
}
but I don't know how to upload the image file, in above code I get exception: Bad state: Cannot set the body fields of a Request with content-type "multipart/form-data".
How should I write the body of request?
Your workaround should work; many servers will accept application/x-www-form-urlencoded as an alternative (although data is encoded moderately inefficiently).
However, it is possible to use dart:http to do this. Instead of using http.post, you'll want to use a http.MultipartFile object.
From the dart documentation:
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'someone#somewhere.com';
request.files.add(http.MultipartFile.fromPath(
'package',
'build/package.tar.gz',
contentType: new MediaType('application', 'x-tar'),
));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.
dio is very easy to use, in this case you can:
Sending FormData:
FormData formData = new FormData.from({
"name": "wendux",
"file1": new UploadFileInfo(new File("./upload.jpg"), "upload1.jpg")
});
response = await dio.post("/info", data: formData)
More details please refer to dio。
This can be achieved using the MultipartRequest class (https://pub.dev/documentation/http/latest/http/MultipartRequest-class.html)
Change the media type and uri as needed.
uploadFile() async {
var postUri = Uri.parse("<APIUrl>");
var request = new http.MultipartRequest("POST", postUri);
request.fields['user'] = 'blah';
request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri("<path/to/file>").readAsBytes(), contentType: new MediaType('image', 'jpeg')))
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
}
I found a working example without using any external plugin , this only uses
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:convert';
Code
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
// get file length
var length = await imageFile.length(); //imageFile is your image file
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": "Bearer " + token
}; // ignore this headers if there is no authentication
// string to uri
var uri = Uri.parse(Constants.BASE_URL + "api endpoint here");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFileSign = new http.MultipartFile('profile_pic', stream, length,
filename: basename(imageFile.path));
// add file to multipart
request.files.add(multipartFileSign);
//add headers
request.headers.addAll(headers);
//adding params
request.fields['loginId'] = '12';
request.fields['firstName'] = 'abc';
// request.fields['lastName'] = 'efg';
// send
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
How to upload image file using restAPI in flutter/dart.
This work for me.
var postUri = Uri.parse("apiUrl");
http.MultipartRequest request = new http.MultipartRequest("POST", postUri);
http.MultipartFile multipartFile = await http.MultipartFile.fromPath(
'file', filePath);
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
print(response.statusCode);
Updated 2021 way:
using flutter http and mime
import 'package:mime/mime.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'dart:io';
Future<dynamic> multipartImageUpload(String baseUrl, String api, File image) async {
var uri = Uri.parse(baseUrl + api);
final mimeTypeData =
lookupMimeType(image.path, headerBytes: [0xFF, 0xD8]).split('/');
// Intilize the multipart request
final imageUploadRequest = http.MultipartRequest('PUT', uri);
// Attach the file in the request
final file = await http.MultipartFile.fromPath('image', image.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
imageUploadRequest.files.add(file);
// add headers if needed
//imageUploadRequest.headers.addAll(<some-headers>);
try {
final streamedResponse = await imageUploadRequest.send();
final response = await http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
print(e);
return null;
}
}
Use MultipartRequest class.
How to upload image file using restAPI in flutter/dart
void uploadImage1(File _image) async {
// open a byteStream
var stream = new http.ByteStream(DelegatingStream.typed(_image.openRead()));
// get file length
var length = await _image.length();
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "image_file" is a key of the API request
var multipartFile = new http.MultipartFile('image_file', stream, length, filename: basename(_image.path));
// add file to multipart
request.files.add(multipartFile);
// send request to upload image
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
name spaces:
import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
UPLOAD IMAGE TO SERVER WITH FORM DATA
To upload image to server you need a dio library.
Features:
Authorization (adding token)
Adding extra field like: username, etc
Adding Image to upload
Code example:
import 'package:dio/dio.dart' as dio;
import 'dart:convert';
try {
///[1] CREATING INSTANCE
var dioRequest = dio.Dio();
dioRequest.options.baseUrl = '<YOUR-URL>';
//[2] ADDING TOKEN
dioRequest.options.headers = {
'Authorization': '<IF-YOU-NEED-ADD-TOKEN-HERE>',
'Content-Type': 'application/x-www-form-urlencoded'
};
//[3] ADDING EXTRA INFO
var formData =
new dio.FormData.fromMap({'<SOME-EXTRA-FIELD>': 'username-forexample'});
//[4] ADD IMAGE TO UPLOAD
var file = await dio.MultipartFile.fromFile(image.path,
filename: basename(image.path),
contentType: MediaType("image", basename(image.path)));
formData.files.add(MapEntry('photo', file));
//[5] SEND TO SERVER
var response = await dioRequest.post(
url,
data: formData,
);
final result = json.decode(response.toString())['result'];
} catch (err) {
print('ERROR $err');
}
To add a header and use http multipart with https://pub.dev/packages/multi_image_picker Plugin,
This is the code.
var request = http.MultipartRequest(
'POST', Uri.parse(myurl)
);
//Header....
request.headers['Authorization'] ='bearer $authorizationToken';
request.fields['PropertyName'] = propertyName;
request.fields['Country'] = country.toString();
request.fields['Description'] = des;
request.fields['State'] = state.toString();
request.files.add(http.MultipartFile.fromBytes(
'ImagePaths',
learnImage,
filename: 'some-file-name.jpg',
contentType: MediaType("image", "jpg"),
)
);
var response = await request.send();
print(response.stream);
print(response.statusCode);
final res = await http.Response.fromStream(response);
print(res.body);
To use HTTP and https://pub.dev/packages/image_picker PLUGIN
This is the code
var request = http.MultipartRequest(
'POST', Uri.parse(myurl)
);
request.headers['Authorization'] ='bearer $authorizationToken';
request.fields['PropertyName'] = propertyName;
request.fields['Country'] = country.toString();
request.fields['Description'] = des;
request.fields['State'] = state.toString();
request.files.add(await http.MultipartFile.fromPath(
'ImagePaths',
file.path
)
);
var response = await request.send();
print(response.stream);
print(response.statusCode);
final res = await http.Response.fromStream(response);
print(res.body);
Working Code
String path = userSelectedImagePath;
Map<String, String> data = {
"name": firstName!,
"email": userEmail!
};
String token = await LocaldbHelper().getToken();
Map<String, String> headers = {
'X-Requested-With': 'XMLHttpRequest',
'authorization': 'Bearer $token',
};
var request = http.MultipartRequest(
'POST',
Uri.parse(ApiUrl.updateProfile),
);
request.fields.addAll(data);
request.headers.addAll(headers);
var multipartFile = await http.MultipartFile.fromPath(
'avatar', path); //returns a Future<MultipartFile>
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
final respStr = await response.stream.bytesToString();
var jsonData = jsonDecode(respStr);
if (response.statusCode == 200) {
// success
} else {
// error
}
Just leaving this here, if anyone is trying to upload a pdf or any other document using MultipartRequest method.
Just add the content type as -
contentType: new MediaType('application', 'pdf')
Good code with Dio and FilePicker for post file on your server. I use flutter for the web.
FilePicker
Dio
First you need writing Dio post method.
Future postImportClient(PlatformFile file) async {
try {
var urlBase = 'your url';
var mfile = MultipartFile.fromBytes(file.bytes!, filename: file.name);
var formData = FormData();
formData.files.add(MapEntry('file', mfile));
await _dio.post(urlBase, data: formData);
} on DioError catch (error) {
throw Exception(error);
}
}
Initial FilePicker and get file.
FilePickerResult? result = await FilePickerWeb.platform.pickFiles();
if (result != null) {
var file = result.files.single;
await client.postImportClient(file);
}
Good luck!
create FormData:
final formDataMap = <String, dynamic>{};
formDataMap["stringKey"] = "string";
List<MultipartFile> multipartImageList = [];
await Future.forEach(imagePaths as List<String>,(String path) async {
final multiPartFile = await MultipartFile.fromFile(
path,
contentType: MediaType("image", "jpeg"),
);
multipartImageList.add(multiPartFile);
});
formDataMap["image[]"] = multipartImageList;
final formData = FormData.fromMap(formDataMap);
With Retrofit & Dio:
#MultiPart()
#POST("{{url}}")
Future<dynamic> uploadFormData(
#Body() FormData formData,
);
With Hearder
upload image
Future uploadImageMedia(File fileImage, String token) async {
final mimeTypeData =
lookupMimeType(fileImage.path, headerBytes: [0xFF, 0xD8]).split('/');
final imageUploadRequest =
http.MultipartRequest('POST', Uri.parse(mainUrlSite + "wp-json/wp/v2/media"));
final file = await http.MultipartFile.fromPath('file', fileImage.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
imageUploadRequest.files.add(file);
imageUploadRequest.headers.addAll({
"Authorization": "Bearer " + token
});
try {
final streamedResponse = await imageUploadRequest.send();
streamedResponse.stream.transform(utf8.decoder).listen((value) {
print(value);
return Future.value(value);
});
} catch (e) {
print(e);
}
}
I use Dio library with put method:
var formData = FormData.fromMap({
'simpleParam': 'example',
'file': await MultipartFile.fromFile(filePath, filename: 'file.jpg')
});
var dio = Dio();
dio.options.headers[HttpHeaders.authorizationHeader] = myToken;
var response = new Response(); //Response from Dio
response = await dio.put(myUrl + "/myApi", data: formData);
The result is in response.data
try {
result[HttpKeys.status] = false;
var request = http.MultipartRequest('POST', url);
request.fields.addAll(body);
if (avatar.path.isNotEmpty) {
request.files.add(await http.MultipartFile.fromPath('uploadedImg', avatar.path));
}
request.headers.addAll(headers);
http.StreamedResponse streamResponse = await request.send();
final response = await http.Response.fromStream(streamResponse);
if (response.statusCode == 200) {
var resMap = jsonDecode(response.body);
debugPrint('<== 𝕊𝕚𝕘𝕟 𝕦𝕡 𝕤𝕦𝕔𝕔𝕖𝕤𝕤𝕗𝕦𝕝𝕝𝕪 ==>');
// debugPrint(response.body);
result[HttpKeys.status] = true;
result[HttpKeys.message] = resMap[HttpKeys.message];
result[HttpKeys.data] = resMap['data'];
return result;
} else {
var resMap = jsonDecode(response.body);
result[HttpKeys.message] = resMap[HttpKeys.message];
return result;
}
} catch (error) {
result[HttpKeys.message] = error.toString();
return result;
}
Here is the code where I am passing Image, route which may be like '/register', and data which is Map<String, String> like data={'directory':'profile'}.
For Uploading Image to Laravel API, Authorization in header is compulsory otherwise it would return "You don't have permission to access this resource". I am passing token as EMPTY string like String token='' as I am uploading
Image at user registration time
This Authorization for read and write is defined in domainurl/public/.htaccess file, you can change it
Try to understand the below code and all the issue would be resolve.
Future uploadImage({
required XFile file,
required String route,
required Map<String, String> data,
}) async {
String url = API_Url + route;
final uri = Uri.parse(url);
try {
http.MultipartRequest request = http.MultipartRequest("POST", uri);
http.MultipartFile multipartFile =
await http.MultipartFile.fromPath('image', file.path);
request.files.add(multipartFile);
request.headers.addAll(_header());
request.fields.addAll(data);
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
print(jsonDecode(response.body));
return jsonDecode(response.body);
} catch (e) {
return null;
}
}
_header() {
return {"Content-Type": "multipart/form-data",
'Authorization': 'Bearer ${token}',
};
}
With dio I do like this:
Future<void> _uploadFileAsFormData(String path) async {
try {
final dio = Dio();
dio.options.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
final file =
await MultipartFile.fromFile(path, filename: 'test_file');
final formData = FormData.fromMap({'file': file}); // 'file' - this is an api key, can be different
final response = await dio.put( // or dio.post
uploadFileUrlAsString,
data: formData,
);
} catch (err) {
print('uploading error: $err');
}
}