Search code examples
node.jsflutterfile-upload

Can't get the flutter posted image to the nodejs server


I want to get the image that have been posted to the nodejs flutter. I am using the below code in the flutter:

  _openCameraPicture(BuildContext context) async {
    var image = await ImagePicker().pickImage(source: ImageSource.camera);
    setState(() async {
      selectedImage = File(image!.path);
      if (Network.isConnected) {
        var request = http.MultipartRequest(
            'POST', Uri.parse("${Network.serverUrl}/upload_image"));
        request.fields['title'] = "testImage";
        request.files.add(http.MultipartFile.fromBytes(
            'picture', selectedImage!.readAsBytesSync(),
            filename: selectedImage!.path.split("/").last));
        var response =
            await request.send().then((value) => {Navigator.pop(context)});
        // if (response.statusCode == 200) {
        //   Do something ...
        // }
      }
    });
  }

In my nodejs server api I use:

router.post("/upload_image", PhoneInfoCtrl.apiUploadImage);

But I can not get the image and upload it to the server. My apiUploadImage is like:

static async apiUploadImage(req, res, next) {
    try {
         console.log(req);

         res.sendStatus(200);
       
    } catch (error) {
        //res.status(500);
    }
}

How may I extract the image from req? I tested some ways but was not possible. Is something wrong with my flutter code?


Solution

  • Solved by using multer in my router in nodejs.

    const path = require('path');
    const multer  = require("multer");
    
    const storage = multer.diskStorage({
        destination : (req, file, cb) =>{
            cb(null , "./public/images")
        },
        filename: (req, file, cb) =>{
            console.log(file);
            cb(null , Date.now() + path.extname(file.originalname));
        },
    });
    

    then:

    router.post("/upload_image", upload.single("picture"),myController.apiUploadImage);