无法从Flutter Assets上传图像

时间:2018-07-28 16:53:17

标签: dart flutter dart-http

我正在尝试将图像从Flutter应用程序上传到名为vize.ai(https://vize.ai/docs)的服务。我为此使用dart:http。

我使用dart:http的MultipartFile请求发送文件。我可以从“文件”手柄上载图像,但是,我无法对资产中的图像执行相同的操作。原因是来自资产的图像被加载为ByteData,然后我将其转换为Uint8List(因为MultipartFileRequest需要一个List)。但是,我不断收到来自服务器的错误请求。

适用于文件处理程序的代码。

  static Future<http.StreamedResponse> uploadTrainingImages(File imageFile) async {
    var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();

    String url = 'https://api.vize.ai/v2/training-image/';
    var request = new http.MultipartRequest('POST', Uri.parse(url));
    request.headers['Authorization'] = "Token " + VIZE_AI_TOKEN;
    var multipartFile = new http.MultipartFile('img_path', stream, length, filename: basename(imageFile.path));
    request.files.add(multipartFile);
    var response = await request.send();
    response.stream.listen((value) {
      print(value);
    });
    return response;
  }

不适用于图片资产的代码:

  static Future<http.StreamedResponse> uploadTrainingImagesFromAssets(String assetName) async {
    try {
      ByteData data = await rootBundle.load(assetName);
      String url = 'https://api.vize.ai/v2/training-image/';
      var request = new http.MultipartRequest('POST', Uri.parse(url));
      request.headers['Authorization'] = "Token " + VIZE_AI_TOKEN;
      var multipartFile = new http.MultipartFile.fromBytes("img_path", data.buffer.asUint8List());
      request.files.add(multipartFile);
      var response = await request.send();
      response.stream.listen((value) {
        print(value);
      });
      return response;
    } catch(e) {
      print(e);
    }
  }

想知道我还需要设置什么(例如MediaType)或其他内容吗?

0 个答案:

没有答案
相关问题