CollectionFS
カテゴリー:Meteor 作成日:2015年2月3日21:57
CollectionFSの使い方
最初にお断り、自分は英語わかりません。
説明を機械翻訳してよんだので、間違っているかも知れません。
プロジェクトの作成
meteor create testCollectionFS
cd testCollectionFS
いつものようにパッケージを読み込みます。
meteor add cfs:standard-packages meteor add cfs:filesystem
画像を縮小する場合は meteor add cfs:graphicsmagick
testCoolectionFS.html
<head>
<title>testCollectionFS</title>
<head>
<body>
<h1>testCollectionFS Test</h1>
{{> myForm}}
</body>
<template name="myForm">
<input type="file" class="myFileInput" name="files[]" multiple />
<template>
testCollection.js 画像関係の場合。
1 var Images = new FS.Collection("images",
2 stores: [
3 new FS.Store.FileSystem("images"),{path: "~/upload"}, {
// 3の {path: "~/upload"} と書くことによって~/uploadフォルダーに読み込んだ画像が格納されます。
// {path: "~/upload"} を書かないと testCollectionFS/.meteor/local/cfs/files/imagesに保存される。リサイズされた画像は testColletionFS/.meteor/local/cfs/files/thumbsに。
4 new FS.Store.FileSystem("thumbs",{
//4の"thumbs"の後に "thumbs",{path:"~/upload/thumbs"}と書くと
//13 gm(readStream).resize(180).stream('PNG').pipe(writeStream);でリサイズされるはずの画像はリサイズされない(ばぐ?)
5 beforeWrite: function(fileObj) {
6 return {
7 extension: 'png',
8 type: 'image/png'
9 };
10 },
// 5~10はリサイズすると同時に png画像へ変換する。この時 要13のstream('PNG')とする事。 stream()とすると壊れたpng画像が格納された。
11 transformWrite: function(fileObj, readStream, writeStream) {
12 // Transform the image into a 10x10px thumbnail
13 gm(readStream).resize(180).stream('PNG').pipe(writeStream);
14 }
// gm を使うため GraphicsMagick をインストールしろとあったので ubuntuserver 14.04 LTSでは、sudo apt-get install graphicsmagick をした。
15 })
16 ],
17 filter: {
18 allow: {
19 contentTypes: ['image/*'] //allow only images in this FS.Collection
20 }
21 }
22});
23if (Meteor.isClient) {
24 // counter starts at 0
25 Template.myForm.events({
26 'change .myFileInput': function(event, template) {
27 FS.Utility.eachFile(event, function(file) {
28 Images.insert(file, function (err, fileObj) {
29 //Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
30 });
31 });
32 }
33 });
34}
35if (Meteor.isServer) {
36 Meteor.startup(function () {
37 // code to run on server at startup
38 });
39}
テキストファイル関係では
testCollectionFS.html
<input type="file" class="myFileInput" name="files[]" multiple />
を
<input type="file" class="myFileInput" name="files[]" />
と multipleをはずした。
testCollectionFS.js
var eventPhotosStore = new FS.Store.FileSystem('eventPhotos', {
path: '~/uploads/full'
});
eventPhotos = new FS.Collection('eventPhotos', {
stores: [eventPhotosStore]
});
events = new Meteor.Collection('events');
if (Meteor.isClient) {
Template.myForm.events({
'change .myFileInput': function(evt) {
var file = evt.target.files[0];
var fileObj = eventPhotos.insert(file);
console.log('Upload result: ', fileObj);
events.insert({
name: file.name,
file: fileObj
});
}
}
のように使うようだ、
簡単にファイル操作ができるようだが、自分のほしかった機能( ローカルのファイルを読み込んで moongodb へ格納する )ではないようだ。
<input type="file" class="myFileInput" name="files[]" multiple />
で multiple は複数同時にファイルを読み込んでくれるので便利ではあるが、メモリーの関係かハングしたようになる場合があるようだ。