使用http包,我可以通过将二进制数据放在post调用的主体中(例如此代码的片段中),将图像发送到服务器:
var response = await http.post('My_url', body: File(path).readAsBytesSync(), headers: {
'apikey': 'myAPIKEY',
'Content-Type': 'image/*', // set content-length
});
我无法通过使用Dio来做同样的事情,我不知道如何将二进制数据直接放入体内(就像我可以用邮递员一样)
答案 0 :(得分:2)
我也遇到过和你一样的情况。在 DIO 中,您必须通过流发送二进制数据。这是我如何实现它的示例,
Uint8List image = File(path).readAsBytesSync();
Options options = Options(
contentType: lookupMimeType(path),
headers: {
'Accept': "*/*",
'Content-Length': image.length,
'Connection': 'keep-alive',
'User-Agent': 'ClinicPlush'
}
);
Response response = await dio.put(
url,
data: Stream.fromIterable(image.map((e) => [e])),
options: options
);
答案 1 :(得分:0)
我已经声明了一个名为'data'的FormData对象,并具有一个图像映射,键为文件名,值为文件路径。 “图像”是服务器端定义的密钥。
data.files.add(MapEntry(
'image',
await MultipartFile.fromFile(image.values.first, filename: "${image.values.first.split("/").last}")
));
答案 2 :(得分:0)
如果有人偶然发现同一问题,只需提出我的解决方案。
我必须在已签名的Google存储URL上上传文件。将文件二进制数据插入PUT请求主体所需的API。无法使用DIO插件实现,我使用DART HTTP包解决了该问题,以下是示例代码。
import 'package:http/http.dart' as http;
await http.put(
Uri.parse(uploadURL),
headers: {
'Content-Type': mimeType,
'Accept': "*/*",
'Content-Length': File(filePath).lengthSync().toString(),
'Connection': 'keep-alive',
},
body: File(filePath).readAsBytesSync(),
);
答案 3 :(得分:0)
在使用 dio 包将二进制数据上传到 google storage api 时,我一直收到 http 403。我能够使用以下方法解决此问题:
Response responseGoogleStorage = await dio.put(
googleStorage.url,
data: File(_imageFile.path).readAsBytesSync(),
options: Options(
headers: {
'Content-Type': contentType,
'Accept': "*/*",
'Content-Length': File(_imageFile.path).lengthSync().toString(),
'Connection': 'keep-alive',
},
),
);