【问题标题】:how to upload files (pdf, doc / image) from file_picker to api server on flutter如何在flutter上将文件(pdf,doc / image)从file_picker上传到api服务器
【发布时间】:2021-06-15 12:43:24
【问题描述】:

如何从 file_picker 上传文件(pdf、doc / image)到 Flutter 上的 api 服务器。

我有一个颤振的项目想要从所选数据上传文件。选择我使用 file_picker 的文件。下面的代码来选择一个文件。

void _openFileExplorer() async {
setState(() => _loadingPath = true);
try {
  _directoryPath = null;
  _paths = (await FilePicker.platform.pickFiles(
    type: _pickingType,
    allowMultiple: _multiPick,
    allowedExtensions: ['jpg', 'pdf', 'doc', 'docx', 'png'],
  ))
      ?.files;
} on PlatformException catch (e) {
  print("Unsupported operation" + e.toString());
} catch (ex) {
  print(ex);
}
if (!mounted) return;
setState(() {
  _loadingPath = false;
  _fileName = _paths != null ? _paths.map((e) => e.name).toString() : '...';
});

}

那怎么上传呢?

【问题讨论】:

    标签: flutter file dart mobile upload


    【解决方案1】:

    我正在使用此功能将文件上传到我的服务器

      static Future<bool> _upload(File file, int id) async {
        var headers = {'Authorization': 'Bearer TOKEN'}; // remove headers if not wanted
        var request = http.MultipartRequest(
            'POST', Uri.parse(BaseUrl + ADD_IMAGE_TO_PRODUCTS)); // your server url
        request.fields.addAll({'id': '$id'}); // any other fields required by your server 
        request.files
            .add(await http.MultipartFile.fromPath('image', '${file.path}')); // file you want to upload 
        request.headers.addAll(headers);
        http.StreamedResponse response = await request.send();
        if (response.statusCode == 200) {
          print(await response.stream.bytesToString());
          return true;
        } else {
          print(response.reasonPhrase);
          return false;
        }
      }
    }

    【讨论】:

      【解决方案2】:

      导入http

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

      使用default构造函数创建MultipartRequest

      var request = http.MultipartRequest('POST', Uri.parse(url));
        request.files.add(
          http.MultipartFile(
            'picture',
            File(filename).readAsBytes().asStream(),
            File(filename).lengthSync(),
            filename: filename.split("/").last
          )
        );
        var res = await request.send();
      

      使用MultipartFile.fromBytes()

        var request = http.MultipartRequest('POST', Uri.parse(url));
        request.files.add(
          http.MultipartFile.fromBytes(
            'picture',
            File(filename).readAsBytesSync(),
            filename: filename.split("/").last
          )
        );
        var res = await request.send();
      

      使用MultipartFile.fromPath()

        var request = http.MultipartRequest('POST', Uri.parse(url));
        request.files.add(
          await http.MultipartFile.fromPath(
            'picture',
            filename
          )
        );
        var res = await request.send();
      

      添加常规文本字段

      var request = http.MultipartRequest('POST', Uri.parse(url));
      request.fields['key'] = 'value';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-25
        • 2020-01-30
        • 2022-12-21
        • 2021-05-20
        • 1970-01-01
        • 1970-01-01
        • 2011-08-17
        相关资源
        最近更新 更多