I need to pick an image from gallery and also have an another field for drag image.
For drag and drop field I used flutter_dropzone.
and used getFileStream(event) data to upload data into server.But file_picker: ^5.2.4 is used to pick image from gallery.So how to get filestream data from this package.
I got bytes but that is not working I needed filestream value
Code using file_picker
void chooseImage() async {
pickedFile = await FilePicker.platform.pickFiles(
type: FileType.custom,
withReadStream: true,
allowedExtensions: [
'jpg','jpeg','png'
]
);
if (pickedFile != null) {
try {
base64 = pickedFile!.files.first.bytes;
base64String.value=base64.toString();
String mime = pickedFile!.files.first.extension.toString();
getS3url("image/$mime" ,base64String.value,from: "cameraIcon");
//withReadStream
//getFileStream(event);
} catch (err) {
print(err);
}
} else {
}
}
Copied from https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';
void main() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: [
'jpg',
'png',
'mp4',
'webm',
],
withData: false,
withReadStream: true,
);
if (result == null || result.files.isEmpty) {
throw Exception('No files picked or file picker was canceled');
}
final file = result.files.first;
final filePath = file.path;
final mimeType = filePath != null ? lookupMimeType(filePath) : null;
final contentType = mimeType != null ? MediaType.parse(mimeType) : null;
final fileReadStream = file.readStream;
if (fileReadStream == null) {
throw Exception('Cannot read file from null stream');
}
final stream = http.ByteStream(fileReadStream);
final uri = Uri.https('siasky.net', '/skynet/skyfile');
final request = http.MultipartRequest('POST', uri);
final multipartFile = http.MultipartFile(
'file',
stream,
file.size,
filename: file.name,
contentType: contentType,
);
request.files.add(multipartFile);
final httpClient = http.Client();
final response = await httpClient.send(request);
if (response.statusCode != 200) {
throw Exception('HTTP ${response.statusCode}');
}
final body = await response.stream.transform(utf8.decoder).join();
print(body);
}
Related
I'm trying to post PaltformFiles to the server using Multipart Requests but keep getting the above error for some strange reason. I would like to know what I can do to resolve this error. The code I have written is given below.
File Picker Method:
onTap: () async {
final filePickerOne = await FilePicker.platform
.pickFiles(
type: FileType.custom,
allowedExtensions: [
'pdf',
'jpg',
'jpeg',
'png'
]);
if (filePickerOne == null) return;
final fileOne = filePickerOne.files.first;
openFile(fileOne);
print('Name: ${fileOne.name}');
setState(() {
fileOneName = fileOne.name;
panDoc = fileOne;
});
print('Bytes: ${fileOne.bytes}');
print('Size: ${fileOne.size}');
print('Extension: ${fileOne.extension}');
print('Path: ${fileOne.path}');
The API Request:
Future<void> postMethod(
String? organizationName,
String? telephoneNumberOne,
String? telephoneNumberTwo,
String? companyPanCard,
PlatformFile? panCard,
String? aadharUdyamUdoyog,
PlatformFile? aadharCard,
String? gstNumber) async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
// final File filePanCard = File(panCard!.path.toString());
// final File fileAadharCard = File(aadharCard!.path.toString());
final url = Uri.parse(baseUrl + 'api/vendor/profile/business/');
var request = http.MultipartRequest('POST', url);
request.headers
.addAll({'Authorization': 'Bearer ${localStorage.getString('token')}'});
request.fields['org_name'] = organizationName!;
request.fields['telephone_1'] = telephoneNumberOne!;
request.fields['telephone_2'] = telephoneNumberTwo!;
request.fields['company_pancard'] = companyPanCard!;
request.files.add(http.MultipartFile.fromBytes(
'company_pancard_doc', File(panCard!.toString()).readAsBytesSync())); //This is where the error gets thrown
request.fields['adhar_udyam_udoyog'] = aadharUdyamUdoyog!;
request.files.add(http.MultipartFile.fromBytes('adhar_udyam_udoyog_doc',
File(aadharCard!.toString()).readAsBytesSync())); //Resolving the aboe error will hopefully resolve this one as well.
request.fields['gst_number'] = gstNumber!;
var response = await request.send();
print('Response: $response');
if (response.statusCode == 200) {
print('Uploaded');
} else {
print('Failed');
}
}
Any Ideas? Do let me know If you more info.
i use file_picker: ^4.2.0 show package for my application.
when i get web release as html, get some Error.
error: path always null in web release
my code to get file:
Future getFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
withReadStream: true,
type: FileType.custom,
allowedExtensions: ['png', 'jpeg', 'jpg', 'pdf'],
);
if (result != null) {
PlatformFile file = result.files.single;
setState(() {
_file = File(file.path.toString());
_filePath = file.path;
});
_uploadFile();
} else {
// file not choose
}
}
i use https://pub.dev/packages/file_picker but in flutter web path not suppor;
you should to use bytes;
i save file bytes in var _fileBytes and use in request;
var request = http.MultipartRequest('POST', Uri.parse('https://.....com'));
request.headers.addAll(headers);
request.files.add(
http.MultipartFile.fromBytes(
'image',
await ConvertFileToCast(_fileBytes),
filename: fileName,
contentType: MediaType('*', '*')
)
);
request.fields.addAll(fields);
var response = await request.send();
function ConvertFileToCast:
ConvertFileToCast(data){
List<int> list = data.cast();
return list;
}
it`s work for me :)
this is my code
Future<File> _imageFile;
void _onImageButtonPressed(ImageSource source) async {
setState(() {
_imageFile = ImagePicker.pickImage(source: source);
});
}
I find this code in flutter documentation but its not work
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'nweiz#google.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new MediaType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
I used file_picker library to pick files. you can use this for pick images as well.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'], //here you can add any of extention what you need to pick
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}
i want to send image to server by jpg format by dio package ,
how can i do this ?
choose image method :
void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
file = file;
print(file);
});
upload image method :
void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
"image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
print(json.decode(onValue));
});
Anyone help me ?
thanks
Please try this
Future<dynamic> _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
"image": await MultipartFile.fromFile(file.path,filename: fileName),
};
return await Dio()
.post(url,data:formData).
then((dynamic result){
print(result.toString());
});
}
You can also use http for this purpose
Future<String> uploadImage(Asset asset,String orderId) async {
// String to uri
Uri uri = Uri.parse('Your URL');
// create multipart request
http.MultipartRequest request = http.MultipartRequest("POST", uri);
ByteData byteData = await asset.getByteData();
List<int> imageData = byteData.buffer.asUint8List();
http.MultipartFile multipartFile = http.MultipartFile.fromBytes(
'image',
imageData,
filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
contentType: MediaType("image", "jpg"),
);
// Add field to your request
request.fields['FieldName'] = fieldValue;
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
// Decode response
final respStr = await response.stream.bytesToString();
return respStr;
}
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;
}
}
}