general_service.dart 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import 'dart:math';
  2. import 'package:camera/camera.dart';
  3. import '../data/session/session_storage.dart';
  4. import '../services/services.dart';
  5. import 'package:http/http.dart' as http;
  6. class GeneralService extends BaseService {
  7. Map<String, String> defaultQueryParameters = {"ordenar": "id-desc"};
  8. Future<http.StreamedResponse> enviarMedia(
  9. {required int id,
  10. required XFile media,
  11. String? modulo,
  12. String? tipo,
  13. String? etiquetaID}) async {
  14. //ejemplo: tipo = imagen, modulo = Visita
  15. final token = await SessionStorage().getToken();
  16. String completo = "$base_url/admin/media/guardar";
  17. String nombre = "generico";
  18. http.MultipartRequest request =
  19. http.MultipartRequest('POST', Uri.parse(completo));
  20. request.headers.addAll({
  21. 'Content-type': 'multipart/form-data',
  22. 'Accept': 'application/json',
  23. 'Authorization': "Bearer $token"
  24. });
  25. if (tipo == "archivo") {
  26. final random = Random();
  27. final randomInt = random.nextInt(99999);
  28. int lastIndex = media.name.lastIndexOf('.');
  29. nombre = "$randomInt";
  30. if (lastIndex != -1 && lastIndex < media.name.length - 1) {
  31. String ext = media.name.substring(lastIndex + 1);
  32. nombre = "$nombre.${ext.toLowerCase()}";
  33. }
  34. nombre = media.name.toString();
  35. }
  36. if (tipo == "imagen") {
  37. final random = Random();
  38. final randomInt = random.nextInt(99999);
  39. nombre = "$randomInt.jpg";
  40. }
  41. if (tipo == "audio") {
  42. final random = Random();
  43. final randomInt = random.nextInt(99999);
  44. nombre = "$randomInt.wav";
  45. }
  46. request.fields[etiquetaID.toString()] = "$id";
  47. request.fields[modulo.toString()] = '1';
  48. request.fields['tipo'] = tipo.toString();
  49. request.files.add(
  50. http.MultipartFile(
  51. 'archivo',
  52. media.openRead(),
  53. await media.length(),
  54. filename: nombre,
  55. ),
  56. );
  57. return await request.send();
  58. }
  59. }