[英]Flutter Retrofit upload file
我正在使用 flutter Retrofit package,正在嘗試將數據上傳到服務器(Laravel)。 基本上,該文件應作為 MultiPart 部分注釋發送。 此外,我應該與文件(在我的情況下是一張圖片)一起發送不同的值,所以我使用了@Part() map<String, dynamic>。
這是我的代碼
@POST('register')
Future<RegisterResponse> register(@Body() Map<String, dynamic> body, @Part() File pic);
這是我的要求
Map<String, dynamic> body = {
"name":" widget.fullName",
"username": "widget.userName",
"phone": "698281556",
"country_code": "+213",
"email": "widget.email@gmail.com",
"birth_date": "18-09-2021",
"pic": imageFile,
"lat": 36.347285,
"lon": 6.603381,
"address": "widget.userName",
"city": "widget.userName",
"residential": "widget.userName",
"device_token": "widget.userName",
"code": "123456",
"tags": [1,2]
};
final logger = Logger();
final dio = Dio(); // Provide a dio instance
dio.options.headers["Content-Type"] =
"multipart/form-data";
dio.options.headers["X-Requested-With"] =
"XMLHttpRequest";
final client = RestClient(dio);
client.register(body,imageFile!).then((it) async {
print(it.access_token);
}).catchError((Object obj) {
// non-200 error goes here.
switch (obj.runtimeType) {
case DioError:
// Here's the sample to get the failed response error code and message
final res = (obj as DioError).response;
logger.e(
"Got error : ${res!.statusCode} -> ${res.data}");
break;
default:
}
});
我不知道為什么它不起作用。 沒有足夠的文檔。 謝謝你的幫助
不幸的是,文檔沒有提到這一點。
您必須使用@Multipart
注釋您的請求才能上傳文件。
您必須注意的另一種情況是,當您使用@Multipart
@Part
所有字段。 甚至那些不是文件的。
一個例子:
@POST('/store')
@MultiPart()
Future<dynamic> store({
@Part() required String title,
@Part() required int part,
@Part() File? attach,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.