目前學習flutter3中,使用的思路都是以前開發iOS的思路。
首先,使用dart:io
啟動HttpService
,部署一個Html文件來作為其他設備訪問的入口頁面。
import 'dart:io';
class HttpServiceLogic {
late HttpServer service;
// 啟動服務
startService() async {
// 啟動 HttpService
service = await HttpServer.bind(InternetAddress.anyIPv4, 25210);
// 這種獲取方式不準 只能獲取到0.0.0.0
print("服務器訪問地址:${service.address.address}:25210");
// 監聽所有Http請求
await service.forEach((HttpRequest request) async {
if (request.uri.path == '/') {
// 入口文件
request.response
..statusCode = HttpStatus.ok
..headers.contentType = ContentType.html
..write(await rootBundle.loadString('assets/www/index.html'))
..close();
} else {
// 其他請求都是404
request.response
..statusCode = HttpStatus.notFound
..close();
}
}
}
//關閉服務
closeService() {
service.close();
}
}
void main() async {
HttpServiceLogic().startService();
}
然后我用ai生成了一個簡單的上傳頁面。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload TXT File</title>
<script>
function uploadFile() {
// 獲取文件輸入框的文件
var file = document.getElementById('fileInput').files[0];
// 創建FormData對象
var formData = new FormData();
formData.append('file', file);
// 創建AJAX請求
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true); // 假設有一個服務端接口 /upload
xhr.onload = function() {
if (this.status === 200) {
console.log(this.responseText);
}
};
xhr.send(formData);
}
</script>
</head>
<body>
<input type="file" id="fileInput" accept=".txt" />
<button onclick="uploadFile()">Upload</button>
</body>
</html>
第二步定一個/upload
接口來接收文件請求,這邊使用 mime庫對multipart/form-data
類型進行解析。
import 'dart:io';
import 'package:mime/mime.dart';
class HttpServiceLogic {
startService() async {
// 啟動 HttpService
service = await HttpServer.bind(InternetAddress.anyIPv4, 25210);
// 這種獲取方式不準 只能獲取到0.0.0.0 可以使用 network_info_plus 組件獲取當前wifi ip
print("服務器訪問地址:${service.address.address}:25210");
// 監聽所有Http請求
await service.forEach((HttpRequest request) async {
if (request.uri.path == '/') {
...
} else if (request.uri.path == '/upload' && request.method.toUpperCase() == 'POST') {
// 上傳接口 這邊定義跟后端寫法差不多
if (request.headers.contentType?.mimeType == 'multipart/form-data') {
// 指定 multipart/form-data 傳輸二進制類型
// 這里使用mime/mime.dart 的 MimeMultipartTransformer 解析二進制數據
// 坑點 使用官方示例會報錯,然后調整以下
String boundary =
request.headers.contentType!.parameters['boundary']!;
// 然后處理HttpRequest流
await for (var multipart
in MimeMultipartTransformer(boundary).bind(request)) {
// 然后在body里面的 filename和field 都在 multipart.headers里面 然后文件流就是multipart本身
String? contentDisposition =
multipart.headers['content-disposition'];
String? filename = contentDisposition
?.split("; ")
.where((item) => item.startsWith("filename="))
.first
.replaceFirst("filename=", "")
.replaceAll('"', '');
// 我這邊指定txt文件,否則跳過,如果不需要就略過
if (filename == null ||
filename.isEmpty ||
!filename.toLowerCase().endsWith('.txt')) {
continue;
}
String path = "自定文件路徑/$filename";
File file = File.fromUri(Uri.file(path));
await file.writeAsBytes(await multipart.toBytes());
// 可以做其他操作
}
// 這邊我直接成功,可以做其他判斷
request.response
..statusCode = HttpStatus.ok
..headers.contentType = ContentType.json
..write({"code": 1, "msg": "upload success"})
..close();
} else {
// 如果不是就報502
request.response
..statusCode = HttpStatus.badGateway
..writeln('Unsupported request')
..close();
}
} else {
...
}
}
}
...
}
最后吐槽一下。我這邊使用查了很多資料都沒有實現方案,包括去了pub
那邊搜索庫的關鍵字multipart
。這個庫 multipart
也是可以使用,但是轉流保存到本地文件會解析不出來。最后還是用ai幫我找到推薦的實現方案,雖然他提供的代碼是不能運行的,起碼推薦了mime
這個庫。