'How to post image to my server from Flutter?
I have a small server based on node JS, which communicates with Post Gre SQL database, and server is working on port 5000. I have route called uploadImage, which uploads an image to the /uploads folder, and uses Bearer token for the authorization. I have not created this server in React, and don't know how to use headers correct in http.multiPartRequest to post image. Code for posting image is here:
const express = require('express');
const router = express.Router();
const pool = require("../database");
const config = require('../config/config');
const expressJwt = require('express-jwt');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const moment = require('moment');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, moment().unix() + '_' + file.originalname);
}
});
var upload = multer({ storage: storage });
router.route('/uploadImage').post(expressJwt({ secret: config.serverSecretKey }),upload.array("files"), async function (req, res) {
let retVal = { msg: '', logoUrl: ''};
try
{
if (req.user == null || req.user === undefined) {res.sendStatus(401); return;}
if (req.user.accountid == null || req.user.accountid === undefined || !req.user.app) {res.sendStatus(401); return;}
let files = req.files;
if(files && files.length > 0 ){
retVal.imageUrl = 'http://localhost:5000/uploads/' + files[0].filename;
}else {
retVal.msg = 'Error';
}
res.status(200).json(retVal);
}catch(err){
console.log({err});
res.status(401);
}
});
My client code is:
onTapUploadImage() async {
final imagePicker = ImagePicker();
final image = await imagePicker.pickImage(source: ImageSource.gallery);
if (image != null) {
final File? imageFile = File(image.path);
if (imageFile != null) {
final SharedPreferences sharedPrefs =
await SharedPreferences.getInstance();
final String? token = await sharedPrefs.getString("token");
final httprequest = await http.MultipartRequest('POST', Uri.parse('http://darivoje.ddns.net:5000/app-api/uploadImage'));
httprequest.headers.addAll({HttpHeaders.authorizationHeader: 'Bearer $token'});
httprequest.files.add(http.MultipartFile.fromString('picture', imageFile.path));
final postreq = await httprequest.send();
}
} else {
print('No image selected.');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
