如何在Dart Flutter中在后台将文件上传到服务器?

时间:2019-04-18 13:49:10

标签: dart flutter

我正在使用multipart / form-data通过应用程序中的POST API(使用dio包)将文件上传到服务器。问题是应用程序必须在后台上载文件(即使用户退出应用程序时)。我该如何实现?将感谢每一个回应!

这是我将文件上传到服务器的方式

Future<bool> upload(File file) async {
    bool isSuccessfull = false;
    var dio = Dio();
    dio.options.baseUrl = "$baseUrl";
    dio.interceptors.add(LogInterceptor(
        requestBody: true,
        request: true,
        responseBody: true));

    try {
      FormData formData = FormData.from({
        "iframeKey": "foofoo",
        "apikey": "foo",
        "secret": "foo",
        "fields": [
          {"key": "first_name", "value": "videoupload"},
          {"key": "larst_name", "value": "videoupload"},
          {"key": "test", "value": "videoupload"},
          {"key": "checkboxtest", "value": "true"},
          {"key": "email_address", "value": "somebody@gmail.com"}
        ],
        "file": [
          new UploadFileInfo(new File(file.path), basename(file.path)),          
        ],
      });

      Response response;
      response = await dio.post("/submit",
          data: formData,
          onSendProgress: showDownloadProgress,
          options: new Options(
            connectTimeout: 100000,
            receiveTimeout: 100000,
            contentType: ContentType.parse("application/x-www-form-urlencoded"),
          ));
      if (response.statusCode == 200) {
        isSuccessfull = true;
      }
    } on DioError catch (e) {
       print(e.message);
    }
    return isSuccessfull;
  }

1 个答案:

答案 0 :(得分:1)

您可以使用flutter_uploader

此插件基于Android中的WorkManager和 iOS中的NSURLSessionUploadTask可在后台模式下运行上传任务。