颤振发布请求到带有文件的服务器



亲爱的,我是颤振的新手,我想将帖子请求从颤振发送到服务器 这是邮递员的要求

图像后请求

帖子标题:

键值

接受:应用程序/json

内容类型:application/x-www-form-urlencode

身份验证后:

熊令牌

帖子正文:

键 : 值

地址 : 地址

描述: 描述

反馈:反馈

媒体:下载.png

我想从颤振发出这个请求 这是我的代码:

File _img; // taken by camera
Map<String,String> headers = {
'Content-Type':'application/json',
'Authorization': 'Bearer $token',
};
final msg = jsonEncode({
"address"    : _address,
"description": _description,
"feedback"   : _techicalSupport,
"media"      : _img;
});

try{
var response = await http.post(
"url",
headers: headers,
body: msg,
);
print("${response.toString()}");
}catch(e){
print("${e.toString()}");
}

我收到此错误: 未处理的异常:"将对象转换为可编码对象失败:"_File"的实例

注意不需要媒体,当我将其从正文中删除时,它可以工作并在数据库中创建记录

我想在正文中包含媒体。 请问我该怎么做...

这是我问题的答案,我使用了Dio库:

import 'package:dio/dio.dart';
File myImage;
List<File> _images = [];

// to handle image and make list of images
_handleImage()async{
File imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
if(imageFile != null){
myImage = imageFile;
_images.add(imageFile);
}
}

// for post data with images
void _submit() async{ 
FormData formData = FormData();
_images.forEach((image) async{
formData.files.addAll(
[
MapEntry(
"media[]",
await dio.MultipartFile.fromFile(image.path),
),
]
);
});
formData.fields.add(MapEntry("address", _address),);
formData.fields.add(MapEntry("description", _description),);
formData.fields.add(MapEntry("feedback", _techicalSupport),);
var response = await new Dio().post(
postUrl,
options: Options(
headers: {
"Content-Type": "application/json",
"Authorization" : 'Bearer $token',
}
),
data: formData
);
print("${response.toString()}");
}

1.配置文件选择器库(可选步骤,您可以使用任何库选择文件(

然后选择文件

File file = await FilePicker.getFile();

2.配置dio库,版本在这里

import 'package:dio/dio.dart';

然后

FormData formData = FormData.fromMap({
"FIELD_NAME_WEBSERVICE_HERE": await MultipartFile.fromFile(imageFile.path,filename: "anyname_or_filename"),
"FIELD_NAME_WEBSERVICE_HERE":"sample value for another field"),
});
var response = await Dio().post("FULL_URL_HERE", data: formData);
print(response);

您需要将_img转换为MultipartFile

MultipartFile file=MultipartFile.fromBytes(
'media', await filePath.readAsBytes(),
filename: 'FILE_NAME');
var request = http.MultipartRequest("POST", Uri.parse(url));
if (files != null) request.files.add(file);

您应该使用 MultipartRequest 来发送文件。

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
void send() async {
final msg = {
"address": "test",
"description": "test",
"feedback": "test",
};
File _img;
var image = await ImagePicker.pickImage(source: ImageSource.camera);
_img = image;
var response = await http.MultipartRequest(
'POST', Uri.parse("url"))
..fields.addAll(msg)
..files.add(http.MultipartFile.fromBytes('image', _img.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'), filename: 'test.jpg'));

print(response);
}

相关内容

  • 没有找到相关文章

最新更新