I have found a easy way to upload images in flutter and then even receiving it on the server.
Flutter:
MaterialButton( color: Colors.blue, child: Text( "Pick Image from Camera", style: TextStyle( color: Colors.white70, fontWeight: FontWeight.bold), ), onPressed: () async { final XFile? photo = await _picker.pickImage(source: ImageSource.camera); print(photo!.path); await uploadImage(photo.path); }, ),
'uploadImage' function:
uploadImage(String filepath) async { var url = 'http://192.168.75.57:4000/upload'; var request = http.MultipartRequest('POST', Uri.parse(url)); request.files.add(await http.MultipartFile.fromPath("img", filepath)); request.fields['_id'] = "abcdef"; request.headers.addAll({ "Content-type": "multipart/form-data", }); var response = request.send(); return response; }
On the server Side: (Nodejs) For this, first install multer (npm install multer)
const multer = require('multer'); const path = require('path') const storage = multer.diskStorage({ destination: './uploads', filename: (req, file, cb) => { cb(null, (new Date()).getTime().toString() + ".jpg"); }, }); const fileFilter = (req, file, cb) => { if (file.mimetype == "image/jpeg" || file.mimetype == "image/png") { cb(null, true); } else { cb(null, false); } }; const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 6, }, fileFilter: fileFilter, });
Finally, honoring the request from flutter application: (In router.js)
router.post('/upload', upload.single("img"), function (req, res) { console.log("hit") console.log(req.body._id) res.send("ok") })
This method worked for me and I found it comparatively easier than other methods.