Flutter Dio : How to Upload Image? - flutter

I'm trying on Postman. And it works
I want upload some image to rest-api using Package DIO Package ,
I'm new for this package (i'm use this package just for CRUD operation) and i'm got problem when upload image operation.
i'm already reading documentation and nothing see for upload images. I'm try this code(ref on documentation) and got some error :
error:FileSystemException
message :"Cannot retrieve length of file"
OSError (OS Error: No such file or directory, errno = 2)
"File: '/storage/emulated/0/Android/data/com.example.mosque/files/Pictures/scaled_IMG_20190815_183541.jpg'"
Type (FileSystemException)
message:FileSystemException: Cannot retrieve length of file, path = 'File: '/storage/emulated/0/Android/data/com.example.mosque/files/Pictures/scaled_IMG_20190815_183541.jpg'' (OS Error: No such file or directory, errno = 2)
DioErrorType (DioErrorType.DEFAULT)
name:"DioErrorType.DEFAULT"
Api.dart
Future uploadImage({dynamic data,Options options}) async{
Response apiRespon = await dio.post('$baseURL/mahasiswa/upload/',data: data,options: options);
if(apiRespon.statusCode== 201){
return apiRespon.statusCode==201;
}else{
print('errr');
return null;
}
}
View.dart
void uploadImage() async {
FormData formData = FormData.from({
"name_image": _txtNameImage.text,
"image": UploadFileInfo(File("$_image"), "image.jpg")
});
bool upload =
await api.uploadImage(data: formData, options: CrudComponent.options);
upload ? print('success') : print('fail');
}
_image is type FILE
I hope who expert with this package can help me with this code and suggest me for upload images.
Thanks.
Full View.dart Code
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mosque/api/api_mosque.dart';
class UploadImage extends StatefulWidget {
#override
_UploadImageState createState() => _UploadImageState();
}
class _UploadImageState extends State<UploadImage> {
ApiHelper api = ApiHelper();
File _image;
TextEditingController _txtNameImage = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_left),
onPressed: () => Navigator.pop(context, false),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.file_upload),
onPressed: () {
uploadImage();
},
)
],
),
body: _formUpload(),
);
}
Widget _formUpload() {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
TextField(
controller: _txtNameImage,
keyboardType: TextInputType.text,
decoration: InputDecoration(hintText: "Nama Image"),
maxLength: 9,
textAlign: TextAlign.center,
),
SizedBox(
height: 50.0,
),
Container(
child: _image == null
? Text('No Images Selected')
: Image.file(_image),
),
SizedBox(
height: 50.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Icon(Icons.camera),
onPressed: () => getImageCamera(),
),
SizedBox(
width: 50.0,
),
RaisedButton(
child: Icon(Icons.image),
onPressed: () => getImageGallery(),
)
],
)
],
),
);
}
void uploadImage() async {
FormData formData = FormData.from({
"name_image": _txtNameImage.text,
"image": UploadFileInfo(File("$_image"), "image.jpg")
});
bool upload =
await api.uploadImage(data: formData, options: CrudComponent.options);
upload ? print('success') : print('fail');
}
getImageGallery() async {
var imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = imageFile;
});
}
getImageCamera() async {
var imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = imageFile;
});
}
}

In Dio latest version, UploadFileInfo method has been replaced by MultipartFile class. And here the way how to use to post image, video or any file:
Future<String> uploadImage(File file) async {
String fileName = file.path.split('/').last;
FormData formData = FormData.fromMap({
"file":
await MultipartFile.fromFile(file.path, filename:fileName),
});
response = await dio.post("/info", data: formData);
return response.data['id'];
}

Even this question is asked a while ago, I believe the main issue is the size of image especially with Laravel.Flutter Image Picker library offers some functionalities to reduce the size of Image, I solved it with bellow steps:
Create a method to get the Image, I am using Camera to Capture the photo
Future getImage() async {
File _image;
final picker = ImagePicker();
var _pickedFile = await picker.getImage(
source: ImageSource.camera,
imageQuality: 50, // <- Reduce Image quality
maxHeight: 500, // <- reduce the image size
maxWidth: 500);
_image = _pickedFile.path;
_upload(_image);
}
Create _upload method to upload the photo, I am using Dio package Dio Package
void _upload(File file) async {
String fileName = file.path.split('/').last;
FormData data = FormData.fromMap({
"file": await MultipartFile.fromFile(
file.path,
filename: fileName,
),
});
Dio dio = new Dio();
dio.post("http://192.168.43.225/api/media", data: data)
.then((response) => print(response))
.catchError((error) => print(error));
}
On the server side, I am using Laravel Laravel, I handle the request as follow
public function store(Request $request)
{
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fullFileName = time(). '.'. $extension;
$file->storeAs('uploads', $fullFileName, ['disk' => 'local']);
return 'uploaded Successfully';
}

In the latest version of Dio :
It should look like this.
String fileName = imageFile.path.split('/').last;
FormData formData = FormData.fromMap({
"image-param-name": await MultipartFile.fromFile(
imageFile.path,
filename: fileName,
contentType: new MediaType("image", "jpeg"), //important
),
});
If without this line.
contentType: new MediaType("image", "jpeg")
Maybe it will cause an error: DioError [DioErrorType.RESPONSE]: Http status error [400] Exception
And get MediaType in this package: http_parser

The following code uploads multiple image files from a dio client to a golang server.
dioclient.dart
FormData formData = FormData.fromMap({
"name": "wendux",
"age": 25,
"other" : "params",
});
for (File item in yourFileList)
formData.files.addAll([
MapEntry("image_files", await MultipartFile.fromFile(item.path)),
]);
Dio dio = new Dio()..options.baseUrl = "http://serverURL:port";
dio.post("/uploadFile", data: formData).then((response) {
print(response);
}).catchError((error) => print(error));
golangServer.go
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func uploadFile(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(200000)
if err != nil {
fmt.Fprintln(w, err)
return
}
formdata := r.MultipartForm
files := formdata.File["image_files"]
for i, _ := range files {
file, err := files[i].Open()
defer file.Close()
if err != nil {
fmt.Fprintln(w, err)
return
}
out, err := os.Create("/path/to/dir/" + files[i].Filename)
defer out.Close()
if err != nil {
fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
return
}
_, err = io.Copy(out, file)
if err != nil {
fmt.Fprintln(w, err)
return
}
fmt.Fprintf(w, "Files uploaded successfully : ")
fmt.Fprintf(w, files[i].Filename+"\n")
}
}
func startServer() {
http.HandleFunc("/uploadFile", uploadFile)
http.ListenAndServe(":9983", nil)
}
func main() {
fmt.Println("Server starts!")
startServer()
}

I have found a solution, where I am uploading file a specific directory which is generated different camera package which requires file path to save jpg file in the provided path.
and I was fetching file name with path and passing to
DIO package
which was giving file length issue, to I have implemented below steps to solve the issue
get File Name With Full Path from directory
create a File from the Path
File(directoryFilePathWithExtension);
and pass File.path to the dio package
MultipartFile.fromFile(
File(directoryFilePathWithExtension).path,
filename: DateTime.now().toIso8601String(),
)

Use UploadFileInfo.fromBytes if you're working with memory images (The error message above shows that your file is invalid and doesn't exist).

Hi there are many issue in file upload
try in android Api 21 because it did not have android permissions if api is working in android api 21 then it wil also work on above versions.
you might not able to get the file in above android version
you just need
FormData formData = FormData.fromMap({
"av_document": await MultipartFile.fromFile(_filePath,filename:
_fileName),
});
to upload any file or image to server and one more thing to note
_filePaths = await FilePicker.getMultiFilePath(type: _pickingType,
fileExtension: _extension);
_fileName = _filePath.split('/').last
by using this process u can upload file or image to server

I am using
dio: ^4.0.6 (for uploading)
flutter_native_image: ^0.0.6+1 (for reducing image size)
to reduce file size
File? compressedFile = profileImage.value == null
? null
: await FlutterNativeImage.compressImage(
profileImage.value?.path ?? '',
quality: 20,
percentage: 60);
dio formData map
var formData = dio.FormData.fromMap({
"name": input['name']!.text,
"profile_pic": await dio.MultipartFile.fromFile(compressedFile.path),
"birth_date": input['dob']!.text,})
request ->
response = await _dio.post(url, data: formData);

Related

Cannot upload image chosen from gallery on Flutter: "Cannot extract a file path from a blob"

I have this image uploading API:
http://localhost:1234/simpleApi/image/upload
Given an image file test_image.jpg, here's how you upload it via HTTPie:
http POST http://localhost:1234/simpleApi/image/upload file#test_image.jpg
If uploaded succesfully, an UUID will be returned.
Now I'm trying to do the same thing on Flutter, first pick the image from gallery, then call the image upload API:
pickImage() async {
XFile? result;
try {
result = await ImagePicker().pickImage(
source: ImageSource.gallery,
imageQuality: 70,
maxWidth: 1024,
);
} on PlatformException {
Get.snackbar('', 'Cannot access gallery...');
}
if (result != null) {
setState(() {
_imgPath = result!.path;
});
}
}
uploadImage(String pathToFile) async {
var IMAGE_UPLOAD_URL = 'http://localhost:1234/simpleApi/image/upload'
var postUri = Uri.parse("IMAGE_UPLOAD_URL");
var request = new http.MultipartRequest("POST", postUri);
request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri(Uri.parse(pathToFile)).readAsBytes(),
contentType: new MediaType('image', 'jpeg')));
request.send().then((response) {
if (response.statusCode == 200) print("Upload OK");
else ("Upload failed.");
});
}
After calling pickImage, it returns a value like this:
blob:http://localhost:64692/a4b07098-0e83-46e2-8bdd-7a0a93aedec3
Passing that value to uploadImage gives this error:
Error: Unsupported operation: Cannot extract a file path from a blob
URI
How to fix this? I tested this on Flutter 2.2.3
You have everything right, the only thing you have to take note of is which platform are you reading this image from, when you check the example on Pub.dev you will notice that you have to check using kIsweb, that way the system will read your blob as a network image.
Obx(() => controller.filepath.value == ""
? Text(
"Select image",
style: TextStyle(fontSize: 20),
)
: Semantics(
label:
'image_picker_example_picked_image',
**child: kIsWeb
? Image.network(
controller.filepath.value)
: Image.file(
File(controller.filepath.value)),
)**
instead of URI you can use this
http.MultipartFile.fromBytes(
'image',
uint8list,
filename: imageName,
);

Unable to load pdf from url using Syncfusion_flutter_pdf

I am working on an application that requires me to load pdf from url. The plugin I am using is syncfusion_flutter_pdf. I couldn't find a direct way to do the same so I tried downloading the file first and then use it. But the pdf is not displaying for some reason! There were nothing in the logs. Can you guys please tell me what went wrong?
fileDownload() async {
tempDir = await getApplicationDocumentsDirectory();
tempPath = tempDir.path + 'flutter-succinctly.pdf';
final dio = Dio();
if (await File(tempPath).exists()) {
//print('tempPath exists at: $tempPath');
if (await File(tempPath).length() == 0) {
dio.download(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
tempPath,
);
} else {
_readPDF();
}
} else {
print('path does not exist');
dio.download(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
tempPath);
}
}
Future<void> _readPDF() async {
final PdfDocument document =
PdfDocument(inputBytes: File(tempPath).readAsBytesSync());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
child: const Text('Generate PDF'),
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.lightBlue,
onSurface: Colors.grey,
),
onPressed: fileDownload,
)
],
),
));
}
We do not have direct support to load PDF from URL. We can load and read PDF data by using http package. We have created a sample to read the PDF data from webspace/website to load and save it using the retrieved PDF data. Kindly try the following code example and sample in your side,
Add http package in dependencies section of pubspec.yaml file
dependencies:
http: ^0.13.3
Import the following package in your dart file.
//Read an PDF data from website/webspace
import 'package:http/http.dart' show get;
Get image data
//Read an PDF data from website/webspace
var url = "https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf";
var response = await get(Uri.parse(url));
var data = response.bodyBytes;
Load data into PDF document
//Create a new PDF document
PdfDocument document = PdfDocument(inputBytes: data);
//Save PDF document
final List bytes = document.save();
//Dispose the document.
document.dispose();
Please find the sample from https://www.syncfusion.com/downloads/support/directtrac/general/ze/pdf_sample565926150.

Choose a file (image, pdf, doc) and upload to server flutter android

I'm working with ASP.NET rest APIs. The task is I have to choose only one thing i.e image, pdf, docs file and send it to server. For picking files, I'm using the following library
file_picker: ^3.0.3
After successfully picking the file when I send it to the server, the response from the server is 403 forbidden.
// this is picking image code
ElevatedButton(
onPressed: () async {
FilePickerResult result = await FilePicker.platform.pickFiles();
if (result != null) {
PlatformFile file = result.files.first;
ApiClient.apiClient.uploadDocumentApi(file.path);
}
},
style: ElevatedButton.styleFrom(
primary: kPrimaryColor,
elevation: 0.0,
),
child: Text('Select'),
),
// this is API code
Future<void> uploadDocumentApi(String filePath) async {
print('pathh: ' + filePath);
String url = 'www.example.com';
var request = http.MultipartRequest(
'POST',
Uri.parse(url),
);
// request.files.add(await http.MultipartFile.fromPath('', filePath));
request.files.add(
http.MultipartFile(
'',
File(filePath).readAsBytes().asStream(),
File(filePath).lengthSync(),
filename: filePath.split("/").last,
),
);
http.StreamedResponse response = await request.send();
print(response.statusCode);
print(response.reasonPhrase);
if (response.statusCode == 200) {
print('success');
print(response.stream.bytesToString());
} else {
print('fail');
print(response.reasonPhrase);
}
}
As the error code indicates its related to authentication of your request. make sure your set your jwt correctly in your request header if needed and check it with backend side

Flutter Web multipart formdata file upload progress bar

I'm using Flutter web and strapi headless cms for backend. I'm able to send the files successfully, but would like its progress indication. Backend restrictions: File upload must be multipart form-data, being it a buffer or stream. Frontend restrictions: Flutter web doesn't have access to system file directories; files must be loaded in memory and sent using its bytes.
I'm able to upload the file using flutter's http package or the Dio package, but have the following problems when trying to somehow access upload progress:
Http example code:
http.StreamedResponse response;
final uri = Uri.parse(url);
final request = MultipartRequest(
'POST',
uri,
);
request.headers['authorization'] = 'Bearer $_token';
request.files.add(http.MultipartFile.fromBytes(
'files',
_fileToUpload.bytes,
filename: _fileToUpload.name,
));
response = await request.send();
var resStream = await response.stream.bytesToString();
var resData = json.decode(resStream);
What I tryed:
When acessing the response.stream for the onData, it only responds when the server sends the finished request (even though the methods states it's supposed to gets some indications of progress).
Dio package code
Response response = await dio.post(url,
data: formData,
options: Options(
headers: {
'authorization': 'Bearer $_token',
},
), onSendProgress: (int sent, int total) {
setState(() {
pm.progress = (sent / total) * 100;
});
The problems:
It seems the package is able to get some progress indication, but Dio package for flutter web has a bug which has not been fixed: requests block the ui and the app freezes until upload is finished.
Hi you can use the universal_html/html.dart package to do the progress bar, here are steps:
to import universal package
import 'package:universal_html/html.dart' as html;
Select files from html input element instead using file picker packages
_selectFile() {
html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = false;
uploadInput.accept = '.png,.jpg,.glb';
uploadInput.click();
uploadInput.onChange.listen((e) {
_file = uploadInput.files.first;
});
}
Create upload_worker.js into web folder, my example is upload into S3 post presigned url
self.addEventListener('message', async (event) => {
var file = event.data.file;
var url = event.data.uri;
var postData = event.data.postData;
uploadFile(file, url, postData);
});
function uploadFile(file, url, presignedPostData) {
var xhr = new XMLHttpRequest();
var formData = new FormData();
// if you use postdata, you can open the comment
//Object.keys(presignedPostData).forEach((key) => {
// formData.append(key, presignedPostData[key]);
//});
formData.append('Content-Type', file.type);
// var uploadPercent;
formData.append('file', file);
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
console.log(e.loaded + "/" + e.total);
// pass progress bar status to flutter widget
postMessage(e.loaded/e.total);
}
});
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
// postMessage("done");
}
}
xhr.onerror = function () {
console.log('Request failed');
// only triggers if the request couldn't be made at all
// postMessage("Request failed");
};
xhr.open('POST', url, true);
xhr.send(formData);
}
Flutter web call upload worker to upload and listener progress bar status
class Upload extends StatefulWidget {
#override
_UploadState createState() => _UploadState();
}
class _UploadState extends State<Upload> {
html.Worker myWorker;
html.File file;
_uploadFile() async {
String _uri = "/upload";
final postData = {};
myWorker.postMessage({"file": file, "uri": _uri, "postData": postData});
}
_selectFile() {
html.InputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = false;
uploadInput.click();
uploadInput.onChange.listen((e) {
file = uploadInput.files.first;
});
}
#override
void initState() {
myWorker = new html.Worker('upload_worker.js');
myWorker.onMessage.listen((e) {
setState(() {
//progressbar,...
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
RaisedButton(
onPressed: _selectFile,
child: Text("Select File"),
),
RaisedButton(
onPressed: _uploadFile,
child: Text("Upload"),
),
],
);
}
}
that's it, I hope it can help you.

What a file type is it 'File$' and how can it be made to type 'File' in flutter

I'm making functionality to be able to upload images to firebase storages through the Flutter Web. I need a list a files, where each file is 'File' type, but i get a type 'File$'.
import 'dart:io' as io;
SpeedDial(
animatedIconTheme: IconThemeData(size: 22.0),
child: Icon(Icons.add),
closeManually: false,
children: [
SpeedDialChild(
child: Icon(Icons.photo_library),
label: translate('agreement.image_uploader.select_images_button', context: context),
onTap: () => _callAddImagesFromWeb(context)),
],
)
_callAddImagesFromWeb(BuildContext context) async {
print('Called _callAddImagesFromWeb: upload images from web app');
html.InputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = true;
uploadInput.click();
uploadInput.onChange.listen((changeEvent) {
print("User added images, length: " + uploadInput.files.length.toString());
allProcessAmount = uploadInput.files.length;
doneProcessAmount = 0;
uploadFile(uploadInput.files);
});
}
Method uploadFile get a list of Files and i need to storage each file to Firebase storage, but when i take one element from list, i get an error that ** Error: Expected a value of type 'File', but got one of type 'File$' **
Future uploadFile(List list) async {
// EXCEPTION IS HERE
io.File image = list.first;
var fileName = new DateTime.now().millisecondsSinceEpoch.toString();
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('agreements/' + widget.agreement.id + '/' + fileName);
StorageUploadTask uploadTask = storageReference.putFile(image);
await uploadTask.onComplete;
print('File Uploaded');
storageReference.getDownloadURL().then((fileURL) {
print(fileURL);
});
}