【发布时间】:2020-10-13 10:16:17
【问题描述】:
我目前正在使用 multi_image_picker: ^4.7.14 上传多个图像,并尝试在 dio: ^3.0.10 多部分请求。
尝试了两种方法
void uploadProduct() async {
var uri = Uri.parse(Constant.postAdUrl);
Map<String, String> headers = {'Content-Type' : 'application/json'};
http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.headers.addAll(headers);
request.fields['adcover'] = coverImage;
request.fields['ads_userfkid'] = userId;
request.fields['ads_name'] = widget.title;
request.fields['ads_description'] = widget.description;
request.fields['ads_price'] = widget.price;
request.fields['ads_subcatfkid'] = widget.subId;
request.fields['ads_location'] = widget.location;
List<MultipartFile> newList = new List<MultipartFile>();
for(int i=0; i<images.length; i++){
File imageFile = File(images[i].toString());
var stream = new http.ByteStream(imageFile.openRead());
var length = await imageFile.length();
var multipartFile = new http.MultipartFile('files[]', stream, length, filename:imageFile.path.split('/').last);
newList.add(multipartFile);
}
request.files.addAll(newList);
var response = await request.send();
print(request.fields);
if (response.statusCode == 200) {
print(response);
print("Image Uploaded");
} else {
print("Upload Failed");
}
}
这里我收到一个错误,因为 参数类型 MultipartFile(MultipartFile 在 http-0.12.2 中定义)无法分配给参数类型 MultipartFile(MultipartFile 在 dio-3.0.1 中定义)。 10)
另一方面,我确实喜欢这个
void uploadProduct() async {
print("Inside conversion");
String postUrl = Constant.postAdUrl;
Map<String, String> headers = {'Content-Type' : 'application/json'};
try {
var dio = new Dio();
FormData formData = new FormData.fromMap({
'files[]' : images,
'adcover' : _image,
'ads_subcatfkid' : widget.subId,
'ads_userfkid' : userId,
'ads_name' : widget.title,
'ads_description' : widget.description,
'ads_price' : widget.price,
'ads_location' : widget.location,
});
Response resp = await dio.post(postUrl, data: formData, options: Options(headers: headers));
if(resp.statusCode == 200) {
print(resp.data);
}
} catch(e){
print(e);
}
}
但是这里没有数据被发布到服务器中
【问题讨论】: