Flutter-使用HttpService实现局域网文件传入到app

目前学习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这个库。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容