Flutter -如何上传文件到API?

4szc88ey  于 2023-03-24  发布在  Flutter
关注(0)|答案(2)|浏览(161)

bounty将在5天后过期。此问题的答案可获得+50声望奖励。who-aditya-nawandar正在寻找此问题的更详细答案:到目前为止没有任何工作。我一直得到相同的错误“Null”不是类型转换中类型InstanceRef的子类型。如果您已经成功将文件上传到Flutter Web中的API,请帮助我。

uploadFiles() async {
        ///
        try {
          var token =
              'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIyIiwibmJmIjoxNjc5MzgzMTY5LCJleHAiOjE2NzkzODQ5NjksImlhdCI6MTY3OTM4MzE2OX0.HL5Y39p0cxpbuOhbls-hjq2Nu_xnVGAJ4qacESp1yNw';
          var url =
              Uri.parse("my_url");
          var request = http.MultipartRequest('POST', url);
          Map<String, String> headers = {
            "Authorization": "Bearer $token",
            "Content-type": "multipart/form-data"
          };
          request.headers.addAll(headers);

          request.fields
              .addAll({"facility_id": "46", "module_id": "3263", "id": "1"});

          for (var file in files) {
            var reader = html.FileReader();
            reader.readAsArrayBuffer(file);

            var completer = Completer<List<int>>();
            bool _isCompleted = false; // add this flag

            reader.onLoadEnd.listen((event) {
              if (!_isCompleted) {
                // check if already completed
                _isCompleted = true;
                completer.complete(reader.result as List<int>);
              }
            });
            var filename = file.name;
            var multipartFile = http.MultipartFile.fromBytes(
              'file',
              (await completer.future),
              filename: filename,
            );
            request.files.add(multipartFile);
          }

          var response = await request.send();

          if (response.statusCode == 200) {
            print('Upload successful');
          } else {
            print('Upload failed');
          }
        } //
        catch (e) {
          print(e);
        }
      }

我试图将文件(自在Web上工作以来的HTML文件)发布到API。我收到一个错误,说'Null'不是类型转换中InstanceRef类型的子类型。我不知道是什么导致了这一点。代码中的一切似乎对我来说都很好。

tzcvj98z

tzcvj98z1#

对于文件上传,您应该使用"Content-type": "multipart/form-data"发送

Future<int> uploadFile({File file,String filename,String token})async{
    ///MultiPart request
    var request = http.MultipartRequest(
        'POST', Uri.parse("https://your api url with endpoint"),

    );
    Map<String,String> headers={
      "Authorization":"Bearer $token",
      "Content-type": "multipart/form-data"
    };
    request.files.add(
        http.MultipartFile(
           'file',
            file.readAsBytes().asStream(),
            file.lengthSync(),
            filename: filename,
          contentType: MediaType('image','jpeg'),
        ),
    );
    request.headers.addAll(headers);

    /// optional if require to add other fields then image

    request.fields.addAll({
      "name":"test",
      "email":"test@gmail.com",
      "id":"12345"
    });
    print("request: "+request.toString());
    var res = await request.send();
    print("This is response:"+res.toString());
    return res.statusCode;
  }
}
yzuktlbb

yzuktlbb2#

有两种可能的方法
1 -多部分2 -Base64解码

static Future Uploadingusingmultipart({
    var courseid,
    var feedback,
    var filename,
  }) async {
    try {
      
      var request = http.MultipartRequest(
          'POST',
          Uri.parse(
              '${BaseUrl.baseurl}/apilink'));
      request.headers["authorization"] =  BaseUrl.storage.read("logintoken");

      request.fields['courseid'] =
          "${courseid}";
      request.fields['Feedback'] = "${feedback}";
      if (filename != '') {
        request.files.add(new http.MultipartFile.fromBytes(
            'Image', File(filename).readAsBytesSync(),
            filename: filename.split("/").last));
      }
      var res = await request.send();
      final response = await http.Response.fromStream(res);

      print(response.body);
      return response;
    } catch (e) {
      print(e);
      // return onError(e, "login/Users/login");
    }
  }

在这里,您使用fileupload!.files.single.path上传文件

Uploadingusingmultipart(
        courseid: fieldid,
        feedback: '',
        filename: fileupload!.files.single.path,
      )

另一种方法是使用Base64

final bytes = File(pickedFile!.files.single.path).readAsBytesSync();
 String base64Image ="data:image/png;base64," +base64Encode(bytes);

在这里你正常调用API

相关问题