2

I'm posting a file from the front-end using this code:

final request =MultipartRequest('GET', Uri.parse('http://192.168.0.8:8080/sendfile'));
request.files.add(await MultipartFile.fromPath('fromFilePath', 'file.pdf'));
StreamedResponse response = await request.send();

And then, trying to decode this request in shelf backend using this code:

FutureOr<Response> fileHandler(Request request) async {
  try {
    final _body = await request.readAsString(); //! stacked here
    final _map = jsonDecode(_body);


    List<dynamic> _fromFilePath = [];
    _fromFilePath.add(_map['fromFilePath']);

    return Response.ok('Success');
  } catch (_) {
    return Response.internalServerError(body: 'Internal Server Error');
  }
}

So, my question is, how can I decode the file/files from the request?

1 Answers1

0

I am not sure. I am using the shelf_router but this method uses the Request request too. My code looks like this.

  ..post("/test", (Request request) async {
    Map data = {}, files = {};
    final List<FormData> formDataList = await request.multipartFormData.toList();
    for (FormData formData in formDataList) {
      if (formData.filename == null) {
        String dataString = await formData.part.readString();
        data[formData.name] = jsonDecode(dataString);
      } else if (formData.filename is String) {
        files[formData.name] = await formData.part.readBytes();
      }
    }
    print(data);
    print(files.keys);
    return Response.ok("test");
  })

In my request, I am using form-data and passing these files by using request.files.addAll(fileList);

I hope this will help you :)