Flutter: How to upload photos taken from the camera (and other files) via HTTP
Mục lục bài viết
Flutter: How to upload photos taken from the camera (and other files) via HTTP
We use files all the time. They come and go on our social networks, emails and many other scenarios where are necessaries. Right now as I write this article I am using a file for this.
This is a common feature and knowing how to implement it will open up more possibilities. In this article I want to show you how you can implement an app that uploads files.
Here we will upload photos. We will do something similar to Nubank (one of the most famous fintechs here in Brazil)
So let’s upload files!!
Step 0 — Before we start
For that to happen, we will need:
- An app with access to the camera (to take pictures)
- One way to send requests
- A backend for receiving files
So we’ll build a simples app that can take photos using camera package and our layout is inspired by Nubank app.
Once the layout of the app is ready, we will start implementing the sending of files via HTTP requests. For a wider variety of how to implement this feature we will show you how to send files using packages http (published from dart.dev) and dio (published from flutterchina.club).
Finally, we will present a simple C-Sharp backend that will receive files and process them. Basically the backend is the same used in the following article
you can check it out after finishing the current article.
Step 1 — Let’s build an app
Our inspiration is showed in the following image.
Image 1 — Nubank inspiration
As we already mentioned, this is a part of Nubank app, one of the most famous fintechs here in Brazil.
We won’t build exactly the same, we will reproduce only the mechanism and elements using a horizontal list with cards and when use tap on card the camera will be opened.
First of all let’s create the project using the command
flutter create app_upload
We have two main components in addition to the entry point (main.dart). We’ll have a component called CardPicture and TakePicture. The first one is to show cards like our inspiration and the second is to show camera preview and take picture. Let’s dissect them.
CardPicture
Is a StatelessWidget that can receive two params. One param is a onTap gesture and the other is a path.
Basically when a path is passed to the component it shows the image loaded from path and when a paths isn’t passed the onTap gesture is attached. The result is showed in the following image.
Image 2 — CardPicture
Below we can see and understand the code of this component.
CardPicture can receive a function in onTap and a string in imagePath. In the build method you can see the check for imagePath.
If imagePath is not null the component render a Card() with a decorated Container(), otherwise the component render a Card() with an InkWell() wrapping Container().
With InkWell()
we can attach the onTap gesture and call the provided onTap function (line 54)
The decorated container uses BoxDecoration()
and DecorationImage()
to show the image from path (lines 20–24).
TakePhoto
Is a StatefulWidget that receives a CameraDescription
in the constructor and shows a CameraPreview
. It will be used in the onTap gesture handler in CardPicture
component. The component rendered is showed below.
Image 3 — TakePhoto widget
Check the code of this component:
This component uses come components of camera package that can be installed using the command flutter pub add camera
.
The key points in this widget are:
- initState() method — In the
initState()
we instantiate and initialize the_cameraController
object. This object is used to control the camera and take pictures. - takePicture() method — Uses the
_cameraController
to take picture. This method returns aXFile
that is a cross-platform abstraction ofFile
. FromXFile
we can getpath
,mimeType
,name
,length
and some other file information generated from the camera, in our case a photo. - build() method — In the build we use a simple Scaffold with an
AppBar()
and aFloatingActionButton()
that calls takePicture() method in the onTap gesture handler. In thebody
we have aFutureBuilder()
attached to_cameraController
initialization. When done it shows theCameraPreview
fromcamera
package otherwise it shows a circular loader.
MyHomePage
Is a modified version of created componente after run flutter create
command. We made changes in the build method using a Scaffold with SingleChildScrollView in the body as you can see below.
The key points in this widget are:
initState() — Here, using the camera package, we get available cameras in the the device. In addition we filter the cameras to get backside camera only (you can change this if you need/want). After get the desired camera we set in the _cameraDescription
using setState()
.
build() — In the build method we draw the main widget that is showed in the Image 2. Basically we have a SingleChildScrollView
with a Column
to accommodate widgets vertically.
Vertically we have a Text
, Container
with a horizontalListView
with cards and a Padding
widget that contains a RawMaterialButton
.
onPressed from RawMaterialButton — This Gesture uses the services instances to send pictures (lines 181–203). We’ll focus on these services next steps.
Other interesting methods are presentLoader and presentAlert which are abstractions for displaying loader and alert dialog respectively.
Step 2 — Flutter http package
http
is a package developed from Dart Team and from Pub Dev we have:
This package contains a set of high-level functions and classes that make it easy to consume HTTP resources. It’s multi-platform, and supports mobile, desktop, and the browser.
It makes work with HTTP requests more easily and flexible. Here are an example of how to call an endpoint using http.dart.
import 'package:http/http.dart' as http;
...
var url = Uri.parse('https://example.com/whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
Define url
using URI.parse
and call using methods from http
. In the above example we made a POST
request. Note the response information retrieving like statusCode
and body
.
Step 3 — Flutter dio package
dio
is a package published by flutterchina.club
. It makes the same what http
does but little different. It has more encapsulated things and has somes features to solve problems like caching request, base requestes and more.
import 'package:dio/dio.dart';
...
var dio = Dio();
final response = await dio.get('https://google.com');
print(response.data);
In the above example shows how to make a GET
request using Dio. Basically we instance a dio
object and with it we can make request methods.
Step 4 — Prepare photo to send
It’s time to get ready to upload files to our backend. Basically, we will create two services. The two services will do the same thing which is to send files via POST, the difference is that one will do it using http
and the other using dio
.
HttpUploadService
Below you can see the full code of HttpUploadService.
The key points are:
uploadPhotos — The only method in the class. This method receives a List of strings where each item in the list is the file path.
In the body of the method we instance URI (line 8) and put it into a MultipartRequest instance (line 9) and add files from loop for (line 11).
http.MultipartRequest instance — Instance responsible to send a multipart request as the name suggests.
We instance it passing the request method and the URI (line 9). The instance of http.MultipartRequest
has an attribute called files
that is as List of http.MultipartFile
.
As you can see in the line 11 we add files from each item using http.MultipartFile.fromPath
that receives the field name and the path.
NOTE: In this case you will prepare an array with the field called files. If you want a different field name for each file, you can change it for each.
http.StreamedResponse instance — After call send()
method from request we get a http.StreamedResponse
instance.
With this instance we can get the response. In the line 15 we get responseBytes from response.stream.toBytes()
. Once we have the bytes we can convert it to JSON string using utf8.decode
from dart:convert
package (line 16).
DioUploadService
Belo you can see the full code of DioUploadService.
The key points are:
uploadPhotos — The only method in the class. This method receives a List of strings where each item in the list is the file path.
In the body of the method we define a List of MultipartFile
(line 7) and fill it from loop of paths
using MultipartFile.fromFile
passing file path.
FormData instance — In the line 10 we define a formData. Here FormData is like FormData from Web APIs (see references) and when we pass it to Dio request it will be automatically a Multipart Request.
Our FormData instance is made from FormData.fromMap
and we define files
field. No that the name is the same name used in the HttpUploadService. This name should be files
because our backend expect it.
Dio().post() — Here is where the request is sent. We need only pass the URL and the data
with FormData
instance.
Step 5 — Our backend
Our backend code is a simples Controller from Dotnet Web API and it looks like:
It doesn’t matter if you don’t know C#
. Here what you need to understand is that when calling the endpoint /upload-multiple
the UploadMultiple
method of the ProfileController
class is executed.
In the method parameter we can see the instruction [FromForm(Name = "files")] List<IFormFile> files
that basically receives the files. Note the Name = "files"
where we map the input payload to object in the method. This is why the file array field name must be files.
The backend only receives files and returns information on how many files were sent.
You can build your own backend using your preferred technologies. The purpose of this article isn’t the backend here we are just introducing you to a better understanding of how backend and frontend communication works in this case.
Step 6 — Results
After all the work we’ve done here it’s time to test our app. So open the app, take at least two photos and tap the send button. After doing this, you will see results like the ones shown below.
Image 4 — Result in frontend
If you check in the onPress gesture of SEND button you’ll see the the method call the backend and show the response in using alert dialog.
In the Visual Studio Code logs the result will be looks like showed below.
Image 5 — Result of SEND button tap in the terminal
These informations come from method uploadPhotos of two services. Remember that in the methods we use print
to show informations of request.
Summary
Hey, we did it. We now have an app that upload files. Yep, in our example we used photos from camera but you can upload any file once you have the file path.
Our simple app aggregate some interesting concepts like camera usage, file manipulation, http requests and upload. You can now expand it more creating awesome apps using same concepts and more.
Read more information in references and more posts in this medium profile and clap this article if it was useful to you.
That’s all. See ya!
References
- Repository with full code — https://github.com/geeksilva97/Medium/tree/master/app_upload
- Dio package — https://pub.dev/packages/dio
- Http package — https://pub.dev/packages/http
- FormData Web API— https://developer.mozilla.org/pt-BR/docs/Web/API/FormData
- Upload file with progress in the web — https://medium.com/swlh/uploading-files-with-progress-monitoring-in-vanillajs-angular-and-vuejs-625e2491821