Skip to content

Instantly share code, notes, and snippets.

@ankibalyan
Last active October 5, 2018 15:26
Show Gist options
  • Save ankibalyan/bbd69e1b08645d61bc9f535afcd8a3a1 to your computer and use it in GitHub Desktop.
Save ankibalyan/bbd69e1b08645d61bc9f535afcd8a3a1 to your computer and use it in GitHub Desktop.
For Meteor-Files https://github.com/VeliovGroup/Meteor-Files http upload simple example
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { FilesCollection } from 'meteor/ostrio:files';
import * as fs from 'fs';
import multer from 'multer';
export const Avatars = new FilesCollection({
collectionName: 'avatars',
allowClientCode: false,
onBeforeUpload: function (file) {
// Allow upload files under 10MB, and only in png/jpg/jpeg formats
if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) {
return true;
} else {
return 'Please upload image, with size equal or less than 10MB';
}
},
downloadRoute: 'cdn/storage/avatars',
storagePath: "/app/uploads/images/avatars",
public: true
});
if (Meteor.isServer) {
const _multerInstanceConfig = { dest: '/tmp' }; // Temp dir for multer
const _multerInstance = multer(_multerInstanceConfig);
WebApp.connectHandlers.use(_multerInstance.single('dp')).use("/api/v1/avatar/upload", Meteor.bindEnvironment(function(req, res, next) {
if (req.file !== undefined && req.file.mimetype.substr(0, 6) == 'image/' && req.headers.authtoken.length) {
const hashedToken = Accounts._hashLoginToken(req.headers.authtoken);
const user = Meteor.users.findOne({ 'services.resume.loginTokens.hashedToken': hashedToken });
if (user) {
Avatars.remove({ 'meta.userId': user._id });
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,
username: user.username
}
};
fs.readFile(req.file.path, function (_readError, _readData) {
if (_readError) {
console.log(_readError);
} else {
Avatars.write(_readData, _addFileMeta, function (_uploadError, _uploadData) {
if (_uploadError) {
console.log(_uploadError);
} else {
console.log('upload data=', _uploadData);
fs.unlink(req.file.path); // remove temp upload
}
});
}
});
});
}
}
res.end();
}))
}
@mgscreativa
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment