Search code examples
node.jsexpressflutterpostdio

Flutter: failed to upload image with dio post request. File uploading but cant open it


File uploading but cant open it. The file is 196 kb, uploaded one on server is 191kb and it is broken(can not open). I have tried with dart http first but same error that I'm getting. Here is what I am doing;

void getFile() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['jpg', 'mp4', 'mov', 'png', 'jpeg'],
      allowMultiple: false,
    );
    if (result != null) {
      PlatformFile file = result.files.first;
      var dio = new Dio();
      dio.options.baseUrl = uri;
      FormData formData = new FormData.fromMap({
        "filename":
            await MultipartFile.fromFile(file.path, filename: file.name),
        // "data": MultipartFile.fromBytes(file.bytes, filename: file.name),
      });
      var response = await dio.post(
        "/upload/${file.path.split('/').last}",
        data: formData,
      );
      if (response.statusCode == 200) {
        print(response);
        // final player = json.decode(response.body);
        // checkState(player);
      } else {
        throw Exception('Failed to upload a file');
      }
    } else {
      // User canceled the picker
    }
  }

Also this is the request on node.js server

service.post("/upload/:filename", function (req, res) {
  console.log(req);
  var filename = path.basename(req.params.filename);
  filename = path.resolve("app/media", filename.replace(/\s/g, ""));
  var dst = fs.createWriteStream(filename);
  req.pipe(dst);
  dst.on("drain", function () {
    console.log("Yukleniyor... ", new Date());
    req.resume();
  });
  req.on("end", function () {
    console.log("Tamamlandi... " + filename);
    res.end(JSON.stringify(MyPlayer));
  });
});

EDIT And this is working example on web cli

const selectedFile = document.getElementById("media").files[0];
  $.ajax({
    type: "POST",
    url: target + "/upload/" + selectedFile.name,
    data: selectedFile,
    processData: false,
    contentType: false,
  }).done(function (data) {
    document.getElementById("label").innerHTML = data;
  });

Solution

  • Since you have tried using Http and Dio and getting same error, then the issue should be on the server not the Flutter code.