我试图实现一个简单的文件上传功能在我的Flutter应用程序。我需要有它的网络和移动的。
///
class FileUploadController extends GetxController {
Rx<File?> file = Rx<File?>(null);
String fileName = '';
var token =
'something';
void pickFile() async {
try {
FilePickerResult? result = await FilePicker.platform.pickFiles(
//type: FileType.image,
allowMultiple: false,
);
if (result != null) {
if (kIsWeb) {
Uint8List? fileBytes = result.files.first.bytes;
fileName = result.files.first.name;
var objFile = await createFileFromBytes(fileBytes);
file.value = objFile;
} //
else {
file.value = File(result.files.single.path!);
}
}
} //
catch (e) {
print(e);
}
}
Future<File> createFileFromBytes(Uint8List? bytes) async {
var cleanString = '';
var lstBytes = bytes!.toList();
// Decode the bytes as a UTF-8 string
String decodedCode = utf8.decode(lstBytes, allowMalformed: true);
if (decodedCode.contains('�')) {
cleanString = decodedCode.replaceAll('�', '');
}
// Create a File object from the decoded string
var file = File.fromRawPath(Uint8List.fromList(cleanString.codeUnits));
return file;
}
void uploadFile() async {
try {
if (file.value == null) {
return;
}
// Set API endpoint URL
Uri uri =
Uri.parse('xxxx');
// Create multipart request
var request = http.MultipartRequest('POST', uri);
request.fields.addAll({
"facility_id": "380",
"module_id": "1",
"id": "3263",
});
// Add file to request
String fieldName = 'files';
fileName = kIsWeb ? fileName : file.value!.path.split('/').last;
var checkFile = file.value;
//// getting error here: Un
var bytesData = await file.value!.readAsBytes();
request.files.add(http.MultipartFile.fromBytes(
fieldName,
bytesData,
filename: fileName,
));
// Set headers
request.headers.addAll({
"Authorization": "Bearer $token",
"Content-Type": "multipart/form-data",
"Content-Length": file.value!.lengthSync().toString(),
"Accept": "*/*",
});
// Send request
var response = await request.send();
// Check response status code
if (response.statusCode == 200) {
print('File uploaded successfully!');
} else {
print('Error uploading file.');
}
} //
catch (e) {
print(e);
}
}
///
}
错误:不支持的操作_命名空间
1条答案
按热度按时间jv2fixgn1#
可能不是你要找的答案,但我可以使用share_plus包从我的flutter应用程序(网络和移动的)上传文件。
作为参考,这是我的代码设置。