Flutter 通过 REST API 端点上传文件

5
我有一个Flutter应用程序,通过REST API与服务器交互,可以获取和显示信息,并向服务器发送文本信息。我想添加发送PDF文件和图像到服务器的功能,但我不知道如何实现。以下是选择文件的代码:
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Another Attempt'),
        centerTitle: true,
      ),
      body: Container(
        alignment: Alignment.topCenter,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            MaterialButton(
              onPressed: () async {
                FilePickerResult result =
                    await FilePicker.platform.pickFiles(allowMultiple: true);

                if (result != null) {
                  List<File> files =
                      result.paths.map((path) => File(path)).toList();
                } else {
                  // User canceled the picker
                }
              },
              child: Text('Upload multiple files'),
              color: Colors.blueAccent,
            ),
            SizedBox(height: 10.0),
            MaterialButton(
              onPressed: () async {
                FilePickerResult result = await FilePicker.platform.pickFiles();

                if (result != null) {
                  File file = File(result.files.single.path);
                } else {
                  // User canceled the picker
                }
              },
              child: Text('Upload single file'),
              color: Colors.blueAccent,
            ),
            SizedBox(height: 10.0),
            MaterialButton(
              onPressed: () {
                _submitData();
              },
              child: Text('Upload single file'),
              color: Colors.blueAccent,
            ),
          ],
        ),
      ),
    );
  }

 void _submitData() async {
    setState(() {});

    var data = {
      'image': file,
      'pdf': files,
     };


    try {
      var res = await Network().postData(data, '/convert-customer');
      var body = json.decode(res.body);
      if (res.statusCode == 200 || res.statusCode == 201) {
        print(res.statusCode);
        print(body);
      } else {}
    } on TimeoutException catch (_) {
      print("Your connection has timedout");
      _formKey.currentState.reset();
    } on SocketException catch (_) {
      print("You are not connected to internet");
      _formKey.currentState.reset();
    }

    setState(() {
      _isLoading = false;
    });
  }


这里是将数据发送到服务器的代码。

  final String _baseUrl = 'http://106.20.34.127/trial/api/v1';

  var token;

  _getToken() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    token = jsonDecode(localStorage.getString('token'))['token'];
  }
  postData(data, apiUrl) async {
    try {
      var _finalUrl = _baseUrl + apiUrl;
      Uri fullUrl = Uri.parse(_finalUrl);
      await _getToken();
      print(fullUrl);
      return await http.post(fullUrl,
          body: jsonEncode(data), headers: _setHeaders());
    } catch (e) {
      print(e);
    }
  }

我该怎么做呢?

1个回答

15

使用 http.MultipartRequest 代替 http.post 处理文件。通常,POST 请求的主体由文本键值对组成。使用多部分 POST 请求,您还可以包括二进制内容的文件(图像、各种文档等),除了常规文本值。

import 'package:http/http.dart' as http;

var req = http.MultipartRequest('POST', Uri.parse(url));

这个req对象有一个名为fields的成员Map,用于存储文本值,以及一个名为filesList,可以向其中添加MultipartFiles。

整个过程中最重要的元素是MultipartFile。它可以通过以下几种方式构建:

  1. 默认的MultipartFile(key, stream, length)构造函数,如果需要从字节流中创建已知长度的文件,则可以使用该函数。

  2. 从字节列表中获取文件的MultipartFile.fromBytes(key, bytes)工厂方法。

  3. 从文本字符串中获取文件的MultipartFile.fromString(key, string)工厂方法。

  4. 从指定路径获取文件的MultipartFile.fromPath(key, path)工厂方法。

例如:使用MultipartFile.fromPath(),您可以编写如下函数:

  (String filename, String url) async {
  var request = http.MultipartRequest('POST', Uri.parse(url));
  request.files.add(
    await http.MultipartFile.fromPath(
      'pdf',
      filename
    )
  );
  var res = await request.send();
}

或者您可以直接使用pub.dev上提供的multipart_request插件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接