Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daominhsangvn/9f2e4419d1f1d02b60c3ddf3febecfdb to your computer and use it in GitHub Desktop.
Save daominhsangvn/9f2e4419d1f1d02b60c3ddf3febecfdb to your computer and use it in GitHub Desktop.
FilesCollection Http method for React-Native
Install `$ meteor add meteorhacks:picker` first
```
import {Meteor} from 'meteor/meteor';
import {Accounts} from 'meteor/accounts-base';
import {FilesCollection} from 'meteor/ostrio:files';
export const MyFiles = new FilesCollection({
collectionName: 'MyFiles',
allowClientCode: true,
downloadRoute: '/download',
// storagePath: 'assets/images/avatars/',
});
if (Meteor.isServer) {
const _multer = require('multer');
const _fs = require('fs');
const _multerInstanceConfig = {dest: '/tmp'}; // Temp dir for multer
const _multerInstance = _multer(_multerInstanceConfig);
Picker.middleware(_multerInstance.single('photo'));
Picker.route('/api/v1/upload', function (params, req, res, next) {
if (!!req.file && !!params.query.userId) {
const user = Meteor.users.findOne({'_id': params.query.userId});
if (user) {
_fs.stat(req.file.path, function (_statError, _statData) {
const _addFileMeta = {
fileName: req.file.originalname,
type: req.file.mimetype,
size: req.file.size,
meta: {
userId: user._id
}
};
_fs.readFile(req.file.path, function (_readError, _readData) {
if (_readError) {
console.log(_readError);
res.writeHead(400, {"Content-Type": "application/json"});
var json = JSON.stringify(_readError);
res.end(json);
} else {
MyFiles.write(_readData, _addFileMeta, function (_uploadError, _uploadData) {
if (_uploadError) {
console.log(_uploadError);
res.writeHead(400, {"Content-Type": "application/json"});
var json = JSON.stringify(_uploadError);
res.end(json);
} else {
console.log('upload data=', _uploadData);
_fs.unlink(req.file.path); // remove temp upload
res.writeHead(200, {"Content-Type": "application/json"});
var json = JSON.stringify(_uploadData);
res.end(json);
}
});
}
});
});
}
else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end('User not found');
}
}
else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end('File not found');
}
});
}
```
Checkout this image for the request info: http://oi67.tinypic.com/25tgc60.jpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment