[嗨,基本上,我想要通过POST发送文件到python服务器端Flask API。
目标是为用户提供文件选择器界面,并在选择所需的.txt
文件后,使用POST请求通过Dio发送该文件。
按钮(窗口小部件)应调用此uploadFile()
函数,并且一切都应由它处理
这是我当前的代码:
import 'package:dio/dio.dart';
import 'dart:html';
import 'package:http/http.dart' as http;
BaseOptions options = new BaseOptions(
baseUrl: "http://localhost:5000",
connectTimeout: 5000,
receiveTimeout: 3000,
);
InputElement uploadInput = FileUploadInputElement();
void uploadFile() async {
uploadInput.click();
uploadInput.onChange.listen((e) {
// read file content as dataURL
final files = uploadInput.files;
final reader = new FileReader();
if (files.length == 1) {
final file = files[0];
reader.onLoad.listen((e) {
sendFile(reader.result);
});
reader.readAsDataUrl(file);
}
});
}
sendFile(file) {
var dio = new Dio(options);
FormData formData = FormData.fromMap({"file": MultipartFile.fromBytes(file), "fileName": 'data.txt'});
dio.post('/upload', data: formData);
//dio.post('/upload', data: FormData.fromMap({'file': 'aaaa'}));
}
这里的问题是FileReader没有readAsBytes
方法,因此我无法使用fromBytes方法将文件作为多部分文件发送。
FileReader仅有的方法是:readAsDataUrl
,readAsArrayBuffer
和readAsText
我不想阅读.txt正文以发送它,我想发送实际的文件。
file_picker
,但似乎它不支持Flutter Web我的尝试基于:file_picker
和其他一些我找不到的东西。
我在React中设法做到的方式是:
FileUploader.js
Is there any plugin or way to upload file to server using flutter web?
Handler.js:
export const UploadButton = ({ handler }) => (
<button onClick={handler.uploadTextFile}>Upload Image</button>
);
export const FileChooser = ({ handler }) => (
<input
ref={ref => {
handler.uploadInput = ref;
}}
type="file"
/>
);
请帮忙吗?我在上面停留了超过4天,还无法在Flutter Web中弄清楚如何解决此问题...
成功完成:
如本async uploadTextFile(ev) {
ev.preventDefault();
this.fileName = uuid.v4();
const data = new FormData();
data.append("file", this.uploadInput.files[0]);
data.append("fileName", this.fileName);
data.append("setOfWords", this.words);
await fetch("http://localhost:5000/upload", {
method: "POST",
body: data
});
中所述:
1。我已将FileReader读取为DataUrl
blog post
2。处理数据,将其转换为Byte
reader.readAsDataUrl(file);
3。要阅读它,请使用 Uint8List _bytesData =
Base64Decoder().convert(file.toString().split(",").last);
List<int> _selectedFile = _bytesData;
:
Multipart.readFromBytes()
4。要发送它,请使用http.request
file = http.MultipartFile.fromBytes('file', _selectedFile,
contentType: new MediaType('application', 'octet-stream'),
filename: "text_upload.txt")
var url = Uri.parse("http://localhost:5000/upload");
var request = new http.MultipartRequest("POST", url);
request.files.add(http.MultipartFile.fromBytes('file', _selectedFile,
contentType: new MediaType('application', 'octet-stream'),
filename: "text_upload.txt"));
request.send().then((response) {
print("test");
print(response.statusCode);
if (response.statusCode == 200) print("Uploaded!");
});