Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: file upload as request body #354

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/codegen/dart/dio.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class DartDioCodeGen {
case ContentType.text:
dataExp = declareFinal('data').assign(strContent);
// when add new type of [ContentType], need update [dataExp].
case ContentType.formdata:
default:
dataExp = declareFinal('data').assign(refer('dio.FormData()'));
}
}
Expand Down
3 changes: 2 additions & 1 deletion lib/consts.dart
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,8 @@ const kSubTypeDefaultViewOptions = 'all';
enum ContentType {
json("$kTypeApplication/$kSubTypeJson"),
text("$kTypeText/$kSubTypePlain"),
formdata("$kTypeMultipart/$kSubTypeFormData");
formdata("$kTypeMultipart/$kSubTypeFormData"),
file("$kTypeApplication/$kSubTypeOctetStream");

const ContentType(this.header);
final String header;
Expand Down
20 changes: 19 additions & 1 deletion lib/models/request_model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class RequestModel {
this.isParamEnabledList,
this.requestBodyContentType = ContentType.json,
this.requestBody,
this.requestFile,
this.requestFormDataList,
this.responseStatus,
this.message,
Expand All @@ -45,6 +46,7 @@ class RequestModel {
final List<bool>? isParamEnabledList;
final ContentType requestBodyContentType;
final String? requestBody;
final String? requestFile;
final List<FormDataModel>? requestFormDataList;
final int? responseStatus;
final String? message;
Expand All @@ -67,8 +69,11 @@ class RequestModel {
requestBodyContentType == ContentType.formdata;
bool get hasJsonContentType => requestBodyContentType == ContentType.json;
bool get hasTextContentType => requestBodyContentType == ContentType.text;
bool get hasFileContentType => requestBodyContentType == ContentType.file;
int get contentLength => utf8.encode(requestBody ?? "").length;
bool get hasBody => hasJsonData || hasTextData || hasFormData;
int get fileContentLength => utf8.encode(requestFile ?? "").length;
bool get hasBody =>
hasJsonData || hasTextData || hasFormData || hasFileContentType;
bool get hasJsonData =>
kMethodsWithBody.contains(method) &&
hasJsonContentType &&
Expand All @@ -81,6 +86,10 @@ class RequestModel {
kMethodsWithBody.contains(method) &&
hasFormDataContentType &&
formDataMapList.isNotEmpty;
bool get hasFileData =>
kMethodsWithBody.contains(method) &&
hasFileContentType &&
fileContentLength > 0;
List<FormDataModel> get formDataList =>
requestFormDataList ?? <FormDataModel>[];
List<Map<String, String>> get formDataMapList =>
Expand Down Expand Up @@ -112,6 +121,7 @@ class RequestModel {
isParamEnabledList != null ? [...isParamEnabledList!] : null,
requestBodyContentType: requestBodyContentType,
requestBody: requestBody,
requestFile: requestFile,
requestFormDataList:
requestFormDataList != null ? [...requestFormDataList!] : null,
);
Expand All @@ -130,6 +140,7 @@ class RequestModel {
List<bool>? isParamEnabledList,
ContentType? requestBodyContentType,
String? requestBody,
String? requestFile,
List<FormDataModel>? requestFormDataList,
int? responseStatus,
String? message,
Expand All @@ -155,6 +166,7 @@ class RequestModel {
requestBodyContentType:
requestBodyContentType ?? this.requestBodyContentType,
requestBody: requestBody ?? this.requestBody,
requestFile: requestFile ?? this.requestFile,
requestFormDataList: formDataList != null ? [...formDataList] : null,
responseStatus: responseStatus ?? this.responseStatus,
message: message ?? this.message,
Expand Down Expand Up @@ -188,6 +200,7 @@ class RequestModel {
requestBodyContentType = kDefaultContentType;
}
final requestBody = data["requestBody"] as String?;
final requestFile = data["requestFile"] as String?;
final requestFormDataList = data["requestFormDataList"];
final responseStatus = data["responseStatus"] as int?;
final message = data["message"] as String?;
Expand Down Expand Up @@ -217,6 +230,7 @@ class RequestModel {
isParamEnabledList: isParamEnabledList,
requestBodyContentType: requestBodyContentType,
requestBody: requestBody,
requestFile: requestFile,
requestFormDataList: requestFormDataList != null
? mapListToFormDataModelRows(List<Map>.from(requestFormDataList))
: null,
Expand All @@ -239,6 +253,7 @@ class RequestModel {
"isParamEnabledList": isParamEnabledList,
"requestBodyContentType": requestBodyContentType.name,
"requestBody": requestBody,
"requestFile": requestFile,
"requestFormDataList": rowsToFormDataMapList(requestFormDataList),
"responseStatus": includeResponse ? responseStatus : null,
"message": includeResponse ? message : null,
Expand All @@ -261,6 +276,7 @@ class RequestModel {
"Enabled Params: ${isParamEnabledList.toString()}",
"Request Body Content Type: ${requestBodyContentType.toString()}",
"Request Body: ${requestBody.toString()}",
"Request File: ${requestFile.toString()}",
"Request FormData: ${requestFormDataList.toString()}",
"Response Status: $responseStatus",
"Response Message: $message",
Expand All @@ -284,6 +300,7 @@ class RequestModel {
listEquals(other.isParamEnabledList, isParamEnabledList) &&
other.requestBodyContentType == requestBodyContentType &&
other.requestBody == requestBody &&
other.requestFile == requestFile &&
other.requestFormDataList == requestFormDataList &&
other.responseStatus == responseStatus &&
other.message == message &&
Expand All @@ -306,6 +323,7 @@ class RequestModel {
isParamEnabledList,
requestBodyContentType,
requestBody,
requestFile,
requestFormDataList,
responseStatus,
message,
Expand Down
2 changes: 2 additions & 0 deletions lib/providers/collection_providers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ class CollectionStateNotifier
List<bool>? isParamEnabledList,
ContentType? requestBodyContentType,
String? requestBody,
String? requestFile,
List<FormDataModel>? requestFormDataList,
int? responseStatus,
String? message,
Expand All @@ -158,6 +159,7 @@ class CollectionStateNotifier
isParamEnabledList: isParamEnabledList,
requestBodyContentType: requestBodyContentType,
requestBody: requestBody,
requestFile: requestFile,
requestFormDataList: requestFormDataList,
responseStatus: responseStatus,
message: message,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:apidash/utils/file_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:apidash/providers/providers.dart';
Expand Down Expand Up @@ -50,6 +51,52 @@ class EditRequestBody extends ConsumerWidget {
.update(selectedId, requestBody: value);
},
),
ContentType.file => Align(
alignment: Alignment.centerLeft,
child: Row(
children: [
Expanded(
child: Theme(
data: Theme.of(context),
child: ElevatedButton.icon(
icon: const Icon(
Icons.snippet_folder_rounded,
size: 20,
),
style: ButtonStyle(
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
),
onPressed: () async {
var pickedResult = await pickFile();
if (pickedResult != null &&
pickedResult.files.isNotEmpty &&
pickedResult.files.first.path != null) {
ref
.read(collectionStateNotifierProvider
.notifier)
.update(selectedId,
requestFile:
pickedResult.files.first.path!);
}
},
label: Text(
ref.watch(selectedRequestModelProvider
.select((value) => value?.requestFile)) ??
kLabelSelectFile,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: kFormDataButtonLabelTextStyle,
),
),
),
),
],
),
),
_ => TextFieldEditor(
key: Key("$selectedId-body"),
fieldKey: "$selectedId-body-editor",
Expand Down
19 changes: 15 additions & 4 deletions lib/services/http_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,28 @@ Future<(http.Response?, Duration?, String?)> request(
Uri requestUrl = uriRec.$1!;
Map<String, String> headers = requestModel.enabledHeadersMap;
http.Response response;
String? body;
Object? body;
try {
Stopwatch stopwatch = Stopwatch()..start();
var isMultiPartRequest =
requestModel.requestBodyContentType == ContentType.formdata;
if (kMethodsWithBody.contains(requestModel.method)) {
var requestBody = requestModel.requestBody;
if (requestBody != null && !isMultiPartRequest) {
var contentLength = utf8.encode(requestBody).length;
var requestFile = (requestModel.requestFile != null &&
requestModel.requestFile!.isNotEmpty)
? File(requestModel.requestFile!)
: null;
if ((requestBody != null || requestFile != null) &&
!isMultiPartRequest) {
var requestFileBytes =
requestBody == null ? await requestFile!.readAsBytes() : null;

var contentLength = requestBody != null
? utf8.encode(requestBody).length
: requestFileBytes!.length;

if (contentLength > 0) {
body = requestBody;
body = requestBody ?? requestFileBytes;
headers[HttpHeaders.contentLengthHeader] = contentLength.toString();
if (!requestModel.hasContentTypeHeader) {
headers[HttpHeaders.contentTypeHeader] =
Expand Down
2 changes: 2 additions & 0 deletions test/models/request_model_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ void main() {
"requestBody": '''{
"text":"WORLD"
}''',
'requestFile': null,
'requestFormDataList': null,
'responseStatus': null,
'message': null,
Expand Down Expand Up @@ -148,6 +149,7 @@ void main() {
"Enabled Params: null",
"Request Body Content Type: ContentType.json",
'Request Body: {\n"text":"WORLD"\n}',
'Request File: null',
'Request FormData: null',
"Response Status: null",
"Response Message: null",
Expand Down