Flutter Dio : How to Upload Image?
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 photoFuture 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 usingDio
package Dio Packagevoid _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 followpublic function store(Request $request){ $file = $request->file('file'); $extension = $file->getClientOriginalExtension(); $fullFileName = time(). '.'. $extension; $file->storeAs('uploads', $fullFileName, ['disk' => 'local']); return 'uploaded Successfully';}
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 mainimport ( "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()}