Skip to content

Commit 54782ec

Browse files
committed
ok
1 parent 8900f68 commit 54782ec

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

lib/pages/carros/upload_api.dart

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import 'dart:async';
2+
import 'dart:convert' as convert;
3+
import 'dart:io';
4+
5+
import 'package:carros/pages/api_response.dart';
6+
import 'package:carros/pages/login/usuario.dart';
7+
import 'package:http/http.dart' as http;
8+
import 'package:path/path.dart' as path;
9+
10+
class UploadApi {
11+
static Future<ApiResponse<String>> upload(File file) async {
12+
try {
13+
String url = "https://carros-springboot.herokuapp.com/api/v2/upload";
14+
15+
Usuario user = await Usuario.get();
16+
Map<String, String> headers = {
17+
"Content-Type": "application/json",
18+
"Authorization": "Bearer ${user.token}"
19+
};
20+
21+
List<int> imageBytes = file.readAsBytesSync();
22+
String base64Image = convert.base64Encode(imageBytes);
23+
24+
String fileName = path.basename(file.path);
25+
26+
var params = {
27+
"fileName": fileName,
28+
"mimeType": "image/jpeg",
29+
"base64": base64Image
30+
};
31+
32+
String json = convert.jsonEncode(params);
33+
34+
print("http.upload: " + url);
35+
print("params: " + json);
36+
37+
final response = await http
38+
.post(
39+
url,
40+
body: json,
41+
headers: headers,
42+
)
43+
.timeout(
44+
Duration(seconds: 30),
45+
onTimeout: _onTimeOut,
46+
);
47+
48+
print("http.upload << " + response.body);
49+
50+
Map<String, dynamic> map = convert.json.decode(response.body);
51+
52+
String urlFoto = map["url"];
53+
54+
return ApiResponse.ok(urlFoto);
55+
} catch (error, exception) {
56+
print("Erro ao fazer upload $error - $exception");
57+
return ApiResponse.error("Não foi possível fazer o upload");
58+
}
59+
}
60+
61+
static FutureOr<http.Response> _onTimeOut() {
62+
print("timeout!");
63+
throw SocketException("Não foi possível se comunicar com o servidor.");
64+
}
65+
}

pubspec.lock

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,13 @@ packages:
116116
url: "https://pub.dartlang.org"
117117
source: hosted
118118
version: "2.1.4"
119+
image_picker:
120+
dependency: "direct main"
121+
description:
122+
name: image_picker
123+
url: "https://pub.dartlang.org"
124+
source: hosted
125+
version: "0.6.1+4"
119126
matcher:
120127
dependency: transitive
121128
description:

pubspec.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ dependencies:
2525
sqflite: ^1.1.6+3
2626
cached_network_image: ^1.1.1
2727
connectivity: ^0.4.3+7
28+
image_picker: ^0.6.1+4
2829

2930
# The following adds the Cupertino Icons font to your application.
3031
# Use with the CupertinoIcons class for iOS style icons.

0 commit comments

Comments
 (0)