我是新的扑动,我面临的问题,而上传文件到API。我尝试过使用FormData和MultiPartFile,但它返回错误。我也在这个视频中使用了代码,但它不起作用:
https://www.youtube.com/watch?v=c2tGUt7FLqY& t = 318年代
谁有解决办法?
好的,我找到了,留给有同样问题的人
if (result != null) {
for (var file in result.files) {
final formData = FormData.fromMap({
...someOtherData,
'file': MultipartFile.fromBytes(file.bytes as List<int>)
});
dio.post(
url,
data: formData,
);
}
}
我明白了。不能使用"文件"因为它使用了"part .io"。库,在Flutter WEB中不支持。所以我们必须使用平台文件使用Flutter WEB支持的'dart.html'库。下面是代码:
addStudent(
{@required token,
@required name,
@required email,
@required password,
@required rollNo,
@required phoneNo,
@required PlatformFile? image,
@required gender}) async {
http.MultipartRequest request = http.MultipartRequest(
"POST",
Uri.parse('Your URL HERE'),
);
request.headers['Authorization'] = 'Bearer $token';
request.fields['name'] = name;
request.fields['email'] = email;
request.fields['password'] = password;
request.fields['gender'] = gender;
request.fields['rollno'] = rollNo;
request.fields['phoneNumber'] = phoneNo;
// Here is the code to upload image to API
request.files.add(new http.MultipartFile(
'image', image!.readStream!, image.size,
filename: image.name));
//-------Send request
await request.send().then((value) async {
//------Read response
String result = await value.stream.bytesToString();
//-------Your response
print(result);
});
}