Program Tip

Meteor로 파일 업로드를 어떻게 처리할까요?

programtip 2020. 10. 16. 08:01
반응형

Meteor로 파일 업로드를 어떻게 처리할까요?


Meteor로 파일 업로드를 처리하는 표준 방법은 무엇입니까?


현재 HTTP 서버와 상호 작용하거나 HTTP와 관련된 작업을 수행하는 방법이없는 것 같습니다.

할 수있는 유일한 일은 Meteor.methods에 의해 노출 된 RPC 메서드를 통해 서버와 대화하거나 노출 된 mongoDB API를 통해 mongoDB와 직접 대화하는 것입니다.


http://filepicker.io를 사용했습니다 . 파일을 업로드하고 S3에 저장하고 파일이있는 URL을 반환합니다. 그런 다음 URL을 DB에 넣습니다.

  1. 파일 선택기 스크립트를 클라이언트 폴더로 가져옵니다.

    wget https://api.filepicker.io/v0/filepicker.js
    
  2. 파일 선택기 입력 태그 삽입

    <input type="filepicker" id="attachment">
    
  3. 시작시 초기화합니다.

    Meteor.startup( function() {
        filepicker.setKey("YOUR FILEPICKER API KEY");
        filepicker.constructWidget(document.getElementById('attachment'));
    });
    
  4. 이벤트 처리기 연결

    Templates.template.events({
        'change #attachment': function(evt){
            console.log(evt.files);
        }
    });
    

이미지 경우 파일을 디스크에 쓰지 않는다는 점을 제외하면 Dario 와 유사한 방법을 사용합니다 . 데이터를 모델의 필드로 데이터베이스에 직접 저장합니다. HTML5 File API 를 지원하는 브라우저 만 지원하면 되므로이 방법 은 저에게 효과적입니다 . 그리고 간단한 이미지 지원 만 필요합니다.

Template.myForm.events({
  'submit form': function(e, template) {
    e.preventDefault();
    var file = template.find('input type=["file"]').files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      // Add it to your model
      model.update(id, { $set: { src: e.target.result }});

      // Update an image on the page with the data
      $(template.find('img')).attr('src', e.target.result);
    }
    reader.readAsDataURL(file);
  }
});

난 그냥 함께 왔어요 파일 업로드의 구현 Meteor.methods 및 HTML5 파일의 API를 사용하여. 당신이 무슨 생각을하는지 제게 알려주세요.


새로운 패키지가 있습니다 : edgee : slingshot . 유성 서버에 파일을 업로드하지는 않지만 유성 서버가 비용이 많이 드는 파일 전송을 처리하는 대신 유성 앱을 제공하는 기본 목표에 집중할 수 있도록하는 것이 더 좋습니다.

대신 클라우드 스토리지 서비스에 파일을 업로드합니다. 현재 AWS S3 및 Google Cloud Files를 지원하지만 향후 Rackspace Cloud Files 및 Cloudinary도 지원할 것입니다.

당신의 유성 서버는 단지 코디네이터 역할을합니다.

직접 및 간접 업로드

또한 매우 다양하고 가벼운 패키지입니다.


이를 허용하는 라우터 라는 분위기 패키지 가 있습니다.

실제로 파일 업로드를 처리하는 가장 좋은 방법은 이제 collectionFS입니다.


이번에 가장 적합한 솔루션은 다음과 같습니다. collectionFS를 사용 합니다 .

meteor add cfs:standard-packages
meteor add cfs:filesystem

고객:

Template.yourTemplate.events({
    'change .your-upload-class': function(event, template) {
        FS.Utility.eachFile(event, function(file) {
            var yourFile = new FS.File(file);
            yourFile.creatorId = Meteor.userId(); // add custom data
            YourFileCollection.insert(yourFile, function (err, fileObj) {
                if (!err) {
                   // do callback stuff
                }
            });
        });
    }
});

섬기는 사람:

YourFileCollection = new FS.Collection("yourFileCollection", {
    stores: [new FS.Store.FileSystem("yourFileCollection", {path: "~/meteor_uploads"})]
});
YourFileCollection.allow({
    insert: function (userId, doc) {
        return !!userId;
    },
    update: function (userId, doc) {
        return doc.creatorId == userId
    },
    download: function (userId, doc) {
        return doc.creatorId == userId
    }
});

주형:

<template name="yourTemplate">
    <input class="your-upload-class" type="file">
</template>

상당히 큰 파일이 필요하지 않거나 짧은 시간 동안 만 파일을 저장하는 경우이 간단한 솔루션이 매우 잘 작동합니다.

귀하의 HTML에서 ...

<input id="files" type="file" />

템플릿 이벤트 맵에서 ...

Template.template.events({
  'submit': function(event, template){
    event.preventDefault();
    if (window.File && window.FileReader && window.FileList && window.Blob) {
      _.each(template.find('#files').files, function(file) {
        if(file.size > 1){
          var reader = new FileReader();
          reader.onload = function(e) {
            Collection.insert({
              name: file.name,
              type: file.type,
              dataUrl: reader.result
            });
          }
          reader.readAsDataURL(file);
        }
      });
    }
  }
});

컬렉션을 구독하고 템플릿에서 링크를 렌더링합니다 ...

<a href="{{dataUrl}}" target="_blank">{{name}}</a>

While this might not be the most robust or elegant solution for large files or a file intensive application it works very well for all kind of file formats if you want to implement simple upload and download/rendering of the files.


You could try uploading directly to amazon S3, doing some tricks with js uploaders and stuff. http://aws.amazon.com/articles/1434


You can see on the meteor roadmap that the feature "File upload pattern" is scheduled for "After 1.0". So we have to wait to see an official way.

For now, one of the best ways is to use "collectionFS" (which is 0.3.x dev preview at the time of writting).

Or inkfilepicker (ex. filepicker.io) as suggested here. It is easy enough to use, although this obviously requires and Internet connection from the user side.

If it just to play around, you could as well take advantage of the html5 feature. Something like that.


here is yet another solution:

https://doctorllama.wordpress.com/2014/11/06/meteor-upload-package-with-jquery-file-upload/

This one is using Blueimp's upload solution that supports chunked uploads, progress bars and more.


To accomplish the same action as the most upvoted answer without the cost of filepicker.io, follow the instructions for this package: https://github.com/Lepozepo/S3

Then to obtain the link, use code similar to below. Finally, plug the url returned by secureLink into the DB.

Template.YourTemplate.events({
  "click button.upload": function() {
    var files = $("input.file_bag")[0].files;
    S3.upload(files, "/subfolder", function(e,r) {
      console.log(r);
      Session.set('secureLink', r.secure_url);
    })
  }
});
Template.YourTemplate.helpers({
  "files": function() {
    return S3.collection.find();
  },

  "secureLink": function() {
    return Session.get('secureLink');
  }
});

참고 URL : https://stackoverflow.com/questions/10099202/how-would-one-handle-a-file-upload-with-meteor

반응형