|
| 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 | +} |
0 commit comments