Meteor-Files 项目教程
1. 项目介绍
Meteor-Files 是一个用于 Meteor.js 的文件管理包,它允许通过 DDP 或 HTTP 协议上传文件到 Meteor 服务器,支持多种存储方式,如本地文件系统、AWS S3、GridFS、Dropbox 和 Google Drive。该包稳定、快速、安全且易于使用,适用于各种前端框架,如 Blaze 和 React。
2. 项目快速启动
安装
首先,通过 Atmosphere 安装 ostrio:files
包:
meteor add ostrio:files
初始化文件集合
在项目中创建一个文件集合,例如 imagesCollection
:
import { Meteor } from 'meteor/meteor';
import { FilesCollection } from 'meteor/ostrio:files';
const imagesCollection = new FilesCollection({
collectionName: 'images',
allowClientCode: false, // 禁止客户端删除文件
onBeforeUpload(file) {
// 允许上传小于 10MB 的 png/jpg/jpeg 文件
if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) {
return true;
}
return '请上传小于 10MB 的图片文件';
}
});
if (Meteor.isClient) {
Meteor.subscribe('files.images.all');
}
if (Meteor.isServer) {
Meteor.publish('files.images.all', function () {
return imagesCollection.find().cursor;
});
}
上传文件
在客户端创建一个文件上传表单:
<template name="uploadForm">
{{#with currentUpload}}
正在上传 <b>{{file.name}}</b>: <span id="progress">{{progress.get}}%</span>
{{else}}
<input id="fileInput" type="file" />
{{/with}}
</template>
在客户端 JavaScript 中处理文件上传:
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import imagesCollection from '/imports/api/images/images.js';
Template.uploadForm.onCreated(function () {
this.currentUpload = new ReactiveVar(false);
});
Template.uploadForm.helpers({
currentUpload() {
return Template.instance().currentUpload.get();
}
});
Template.uploadForm.events({
'change #fileInput'(e, template) {
if (e.currentTarget.files && e.currentTarget.files[0]) {
const upload = imagesCollection.insert({
file: e.currentTarget.files[0],
chunkSize: 'dynamic'
}, false);
upload.on('start', function () {
template.currentUpload.set(this);
});
upload.on('end', function (error, fileObj) {
if (error) {
alert('上传错误: ' + error);
} else {
alert('文件 "' + fileObj.name + '" 上传成功');
}
template.currentUpload.set(false);
});
upload.start();
}
}
});
3. 应用案例和最佳实践
应用案例
- 用户头像上传:用户可以上传个人头像,头像文件存储在服务器上,并在用户资料页面显示。
- 文件共享平台:用户可以上传和下载文件,支持多种文件类型和大小的上传。
最佳实践
- 文件验证:在上传文件之前,使用
onBeforeUpload
钩子验证文件类型和大小,确保上传的文件符合要求。 - 文件存储:根据应用需求选择合适的存储方式,如本地文件系统、AWS S3 或 GridFS。
- 文件安全性:通过设置
allowClientCode
为false
,禁止客户端删除文件,确保文件安全性。
4. 典型生态项目
- pyfiles:Python 客户端,用于与 Meteor-Files 服务进行交互。
- meteor-autoform-file:与 AutoForm 集成,简化文件上传表单的创建。
通过以上步骤,您可以快速上手 Meteor-Files 项目,并将其应用于实际开发中。