我有自定义数据:
File avatar = File('path/to/file');
Map<String, dynamic> data = {
'name': 'John',
'avatar': avatar
}
如何将我的数据作为FormData对象发送到服务器?
我尝试通过循环我的数据来创建MultipartFile
类的对象,但在我的例子中,将文件路径作为文件的字符串实例发送。下面是我的代码:
data.forEach((key, value) {
if (value is File) {
String fileName = value.path.split('/').last;
data.update(key, (value) async {
return await MultipartFile.fromFile(value.path, filename: fileName);
});
}
});
FormData formData = FormData.fromMap(data);
var response = await dio.post("/send", data: formData);
但是使用Dio
,我可以上传类似这样的文件:
FormData formData = FormData.fromMap({
"name": "wendux",
"age": 25,
"file": await MultipartFile.fromFile(file.path,filename: fileName)
});
为什么无法将MultipartFile
动态添加到我的Map
中?
发布于 2021-01-15 19:47:49
您不是在等待数据
await Future.wait(data.map((k, v){
if(v is File){
v = await MultipartFile.fromFile(value.path, filename: fileName);
}
return MapEntry(k, v);
}));
请查看My async call is returning before list is populated in forEach loop
发布于 2021-01-15 21:42:48
你可以不带音频发送它。在这里,我编写了整个代码,包括库和response.Please测试,下面的代码是因为在我的情况下,dio不起作用,而您的情况与我的情况非常相似。
就是send it with simple http request
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';
Map<String, String> headers = {
'Content-Type': 'multipart/form-data',
};
Map jsonMap = {
"name": "wendux",
"age": 25,
};
String imagePath, // add the image path in varible
var request = http.MultipartRequest('POST', Uri.parse(url));
request.headers.addAll(headers);
request.files.add(
http.MultipartFile.fromBytes(
'orderStatusUpdate',
utf8.encode(json.encode(jsonMap)),
contentType: MediaType(
'application',
'json',
{'charset': 'utf-8'},
),
),
);
if (imagePath != null) {
final mimeTypeData = lookupMimeType(imagePath).split('/');
final file = await http.MultipartFile.fromPath('images', imagePath,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
print((mimeTypeData[0].toString())); // tells picture or not
print((mimeTypeData[1].toString())); // return extention
request.files.add(file);
}
http.StreamedResponse streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
print(response.statusCode);
print(response.body);
https://stackoverflow.com/questions/65734895
复制相似问题