使用 Flutter 将文件上传到服务器时出错
Error Uploading file to server with Flutter
我有一个 flutter 应用程序 select 并使用 asp.net 将音频文件上传到服务器 api。
我的flutter代码如下
uploadFile() async {
print(file.path);
var postUri = Uri.parse("http://192.168.1.100:5041/api/fileup/up");
var request = new http.MultipartRequest("POST", postUri);
request.fields['user'] = 'blah';
request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri(Uri.parse(file.path)).readAsBytes(),contentType: MediaType('audio','mp3')
));
request.send().then((response) {
if (response.statusCode == 200) {
print("Uploaded!");
}else{
print(response.reasonPhrase);
}
});
}
my file.path 上述 flutter 代码的值是“/data/user/0/com.mydomain.myappname/cache/file_picker/Over_the_Horizon.mp3”,它是从文件选择器返回的。
我可以用 postman 上传文件,但是 flutter 代码给我 500: Internal Server Error
邮递员截图
尝试了在堆栈溢出中发现的几个代码,都给了我同样的错误
你试过DIO吗?
您可以使用 DIO 完成此操作,如下所示:
FormData formData = new FormData.fromMap({
"file": await MultipartFile.fromFile(file.path,
filename: file.path.split('/').last)
});
await dio.post('http://192.168.1.100:5041/api/fileup/up', data: formData, onSendProgress: (int begin, int end) {
var initial = begin;
var done = end;
print('$initial $end');
});
我有一个 flutter 应用程序 select 并使用 asp.net 将音频文件上传到服务器 api。
我的flutter代码如下
uploadFile() async {
print(file.path);
var postUri = Uri.parse("http://192.168.1.100:5041/api/fileup/up");
var request = new http.MultipartRequest("POST", postUri);
request.fields['user'] = 'blah';
request.files.add(new http.MultipartFile.fromBytes('file', await File.fromUri(Uri.parse(file.path)).readAsBytes(),contentType: MediaType('audio','mp3')
));
request.send().then((response) {
if (response.statusCode == 200) {
print("Uploaded!");
}else{
print(response.reasonPhrase);
}
});
}
my file.path 上述 flutter 代码的值是“/data/user/0/com.mydomain.myappname/cache/file_picker/Over_the_Horizon.mp3”,它是从文件选择器返回的。
我可以用 postman 上传文件,但是 flutter 代码给我 500: Internal Server Error
邮递员截图
尝试了在堆栈溢出中发现的几个代码,都给了我同样的错误
你试过DIO吗?
您可以使用 DIO 完成此操作,如下所示:
FormData formData = new FormData.fromMap({
"file": await MultipartFile.fromFile(file.path,
filename: file.path.split('/').last)
});
await dio.post('http://192.168.1.100:5041/api/fileup/up', data: formData, onSendProgress: (int begin, int end) {
var initial = begin;
var done = end;
print('$initial $end');
});