58 lines
1.6 KiB
Dart
58 lines
1.6 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:http/http.dart';
|
|
import 'package:loris/global.dart' as global;
|
|
import 'package:http/http.dart' as http;
|
|
|
|
class FileUpload {
|
|
String description;
|
|
final String path;
|
|
|
|
// media id for identity,
|
|
// gets set after first sucessfully uploading
|
|
Map<String, String> ids = {};
|
|
|
|
FileUpload({
|
|
required this.description,
|
|
required this.path,
|
|
this.ids = const {},
|
|
});
|
|
|
|
static Future<FileUpload> fromPath(String path, String description) async {
|
|
return FileUpload(
|
|
description: description,
|
|
path: path,
|
|
);
|
|
}
|
|
|
|
/*
|
|
sends a media attachments and returns the http status code
|
|
if the status code is 200, the String is the media attachments id,
|
|
otherwise it's the error response
|
|
*/
|
|
Future<MapEntry<int, String>> upload(String identityName) async {
|
|
final identity = global.settings!.identities[identityName]!;
|
|
final headers = {
|
|
...global.defaultHeaders,
|
|
...identity.getAuthHeaders(),
|
|
};
|
|
final uri =
|
|
Uri(scheme: "https", host: identity.instanceUrl, path: "/api/v1/media");
|
|
final request = MultipartRequest(
|
|
"POST",
|
|
uri,
|
|
);
|
|
request.headers.addAll(headers);
|
|
request.files.add(await MultipartFile.fromPath(
|
|
"file",
|
|
path,
|
|
));
|
|
request.fields.addAll({"description": description});
|
|
final response = await http.Response.fromStream(await request.send());
|
|
if (response.statusCode != 200 && response.statusCode != 202) {
|
|
return MapEntry(response.statusCode, jsonDecode(response.body)["error"]);
|
|
}
|
|
return MapEntry(response.statusCode, jsonDecode(response.body)["id"]);
|
|
}
|
|
}
|