Reputation: 3501
I have a Flutter app where users fill a form and add images (upto 5). I want to send this complete data to my node.js server via API.
Here is my flutter code:
List<File> _imageFileList = new List<File>();
var postUri = Uri.parse('https://myapi.herokuapp.com/api/user/new');
var request = new http.MultipartRequest("POST", postUri);
request.headers['Authorization'] = 'Bearer ' + prefs.getString("TOKEN");
request.fields['first_name'] = _firstName;
request.fields['last_name'] = _lastName;
// add file to multipart
request.files.add(
new http.MultipartFile(
'upl',
new http.ByteStream(DelegatingStream.typed(_imageFileList[0].openRead())),
await _imageFileList[0].length()
)
);
// send
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
On my Node.js app I do the following:
var s3 = new aws.S3();
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'mybucketname',
acl: 'public-read',
key: function (req, file, cb) {
console.log(file);
cb(null, file.originalname);
}
})
});
router.post('/new', upload.array('upl'), (req, res) => {
var userObj = req.body;
userObj.uuid = uuidv4();
User.create(userObj).then(user => {
console.log('----- added user: ' + JSON.stringify(user));
res.status(200).json({
message : 'user added'
});
});
});
The problem is in my API call I do get the first and last name and it gets saved, however I do not receive any image(s).
Upvotes: 0
Views: 2687
Reputation: 140
I'm using .fromPath
and this is the code for uploading multiple files. Make sure to set the 'Content-Encoding'
in the header and accept the same in the backend
uploadDocuments(int refId,String token, List<File> fileList) async {
String url = '$baseURL/api/referral/documents/upload';
var uri = Uri.parse(url);
var request = http.MultipartRequest("POST", uri);
request.headers['x-access-token'] = token;
request.headers['Content-Encoding'] = "application/gzip";
request.fields["referralId"] = "$refId";
for (var item in fileList) {
await http.MultipartFile.fromPath('files', item.path,
contentType: MediaType('application', 'x-tar'))
.then((onValue) {
print(onValue);
request.files.add(onValue);
});
}
var response = await request.send();
print(response);
if (response.statusCode == 200) print('Uploaded!');
}
Upvotes: 1