2015-03-12 4 views
2

Доброе утро,загрузить файл с Curl

Я хотел бы знать, если есть способ, чтобы загрузить файл с моего рабочего стола на Meteor сервер в GridFS Store.

Это те пакеты, которые я установил для создания приложения:

accounts-base   1.1.3 A user account system 
accounts-password  1.0.6 Password support for accounts 
accounts-ui   1.1.4 Simple templates to add login widgets to an app 
autopublish   1.0.2 Publish the entire database to all clients 
cfs:gridfs    0.0.31 GridFS storage adapter for CollectionFS 
cfs:standard-packages 0.5.4 Filesystem for Meteor, collectionFS 
ian:bootstrap-3  3.3.1 HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. 
insecure    1.0.2 Allow all database writes by default 
iron:router   1.0.7 Routing specifically designed for Meteor 
meteor-platform  1.2.1 Include a standard set of Meteor packages in your app 
nimble:restivus  0.6.2 Create authenticated REST APIs in Meteor 0.9.0+. Setup CRUD endpoints for Collections. 

Это мой код одного файла:

var fileStore = new FS.Store.GridFS("fileStore"); 
Files = new FS.Collection("Files", { 
    stores: [fileStore] 
}); 

if (Meteor.isClient) { 
    Template.demo.helpers({ 
    files: function() { 
     var objs = Files.find(); 
     return Files.find(); 
    } 
    }); 

    Template.demo.events({ 
    'change #file': function(e, t) { 
     var file = t.find('#file').files[0]; 
     console.log(file.name); 
     var newFile = new FS.File(file); 
     newFile.metadata = { 
     fn: "filename" 
     }; 
     Files.insert(newFile, function (err, fileObj) { 
     if (!err) { 
      var _fId = newFile._id; 
      var _fn = file.name; 
      var _collectionName = newFile.collectionName; 
      var _basePath = "/cfs/files/"; 
      var _downloadPath = _basePath + _collectionName + "/" + _fId; 

      FileList.insert({ 
      _id: _fId, 
      fileName: _fn, 
      collectionName: _collectionName, 
      basePath: _basePath, 
      downloadPath: _downloadPath 
      }); 
     } 
     }); 
    } 
    }); 
} 

if (Meteor.isServer) { 
    Meteor.startup(function() { 
    if (Meteor.users.find({}).count() === 0) { 
     Accounts.createUser({ 
     email : "[email protected]", 
     password : "password", 
     profile : { 
      //publicly visible fields like firstname goes here 
     } 
     }); 
    } 

    // code to run on server at startup 
    console.log("Set Restivus"); 
    Restivus.configure({ 
     useAuth: true, 
     prettyJson: true 
    }); 

    Restivus.addCollection(FileList); 

    Files.allow({ 
     insert: function(){ 
     return true; 
     }, 
     update: function(){ 
     return true; 
     }, 
     remove: function(){ 
     return true; 
     }, 
     download: function(){ 
     return true; 
     } 
    }); 
    }); 
} 

Я попробовал команду:

curl -v -X POST 'http://localhost:3000/cfs/files/Files/' -F '[email protected]"download.jpeg";type=image/jpeg' 

и это выход:

* Hostname was NOT found in DNS cache 
* Trying 127.0.0.1... 
* Connected to localhost (127.0.0.1) port 3000 (#0) 
> POST /cfs/files/Files/ HTTP/1.1 
> User-Agent: curl/7.37.1 
> Host: localhost:3000 
> Accept: */* 
> Content-Length: 5626 
> Expect: 100-continue 
> Content-Type: multipart/form-data; boundary=------------------------955a67d5c4b2f2c4 
> 
< HTTP/1.1 100 Continue 
< HTTP/1.1 501 Not Implemented 
< vary: Accept-Encoding 
< access-control-allow-origin: http://meteor.local 
< access-control-allow-methods: PUT 
< access-control-allow-headers: Content-Type 
< date: Thu, 12 Mar 2015 14:25:55 GMT 
< connection: keep-alive 
< transfer-encoding: chunked 
* HTTP error before end of send, stop sending 
< 
* Closing connection 0 

Команда для чтения файла через CURL вместо работы:

curl -v -X GET 'http://127.0.0.1:3000/cfs/files/Files/d6DAowcAwZcXTKnJ5' 

Не могли бы вы мне помочь или дать пример?

спасибо.

С уважением.

+0

Как говорится в вашей ошибке: 'access-control-allow-methods: PUT'. Вы не можете ОТПРАВИТЬ туда. –

ответ

1

Мне повезло с пакетом Meteor Uploads. Он создает конечную точку загрузки, с которой вы можете отправлять сообщения POST.

+0

Я попробую как можно скорее, и я дам вам отзыв, спасибо. –

+0

Привет, Джеффри, со следующей командой curl -v -X POST 'http://127.0.0.1:3000/upload/' -H 'Content-Type: text/plain; charset = UTF-8 '-T "file.txt" Я получаю эту ошибку с сервера "[Ошибка: плохой заголовок типа контента, неизвестный тип содержимого: text/plain; charset = UTF-8]". Не могли бы вы мне помочь? –

+0

Следуйте инструкциям в пакете, чтобы заставить его работать нормально (т. Е. С формой загрузки в шаблоне Meteor). Используйте эту форму для отправки загрузки и загляните на вкладку «Сеть» вашего браузера Инструменты разработчика, чтобы проверить запрос AJAX POST. Это те заголовки, которые вам придется реплицировать в ваш запрос на завивание. –

Смежные вопросы