How To Upload and Send File With Flutter

wgnalvian
2 min readApr 20, 2023

--

Hi guys, I’m pian and today I’m going tell you a tutorial for uploading and sending file with Flutter

#1 Make a simple Flutter project

To create a flutter project, I will give u example by using command line interface. Open your terminal or similar and type :

flutter create --org com.yourdomain your_app_name

after successfully created, please enter into directory that was created before and open it using your code editor

#2 install the required packages

Before send files with flutter you need to install package file_picker and http. To install it, just type in the terminal command below :

flutter pub add file_picker http

#3 Make a function to select file

Dont forget to import package file_picker

import 'package:file_picker/file_picker.dart';

final pathFile = 'pathToFile';

selectFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
// type params for validate type of file to be selected
type: FileType.custom, allowedExtensions: ['png', 'jpg', 'jpeg']);
if (result != null) {

// you can get name file below
final nameFile = result.files.single.name;
// you can get path file below
pathFile = result.files.single.path.toString();
} else {
// User canceled the picker
}
}

You can trigger to run the function above by using a widget like ElevatedButton or something else and get the file name and path to send later

 ElevatedButton(onPressed: (){

// running function select file
selectFile();

}, child: Text("Upload File"));

#4 Make function to send file

Dont forget to import package http

     import 'package:http/http.dart' as http;

// you can get path file by functon selectFile above
final pathFile = 'pathToFile';

void sendFile() async {
try {
var request = http.MultipartRequest(
'POST', Uri.parse('your_api_url'));

// make field file with key and value using multipartFile
final file = await http.MultipartFile.fromPath(
'field_key_file', pathFile);

// add to request
request.files.add(file);

// add header
request.headers.addAll({
'Authorization': 'your_token_api',
});

// add another field like string value,
request.fields.addAll({
'other_key_field' : 'other_value_field'
});

// send request
final streamResponse = await request.send();
var response = await http.Response.fromStream(streamResponse);
// you can get response body below
print(response.body);
} catch (error) {
// do whatever you want to handle error
}
}

Okay, maybe that’s enough to tell you how to upload and send files with flutter. I know you are a smart person. So thanks and happy coding.

--

--

wgnalvian
wgnalvian

No responses yet