2

在我的流星应用程序中,服务器尝试下载一些文件以将它们存储在文件系统中。我使用 Meteor.http 包来执行此操作,但实际上,如果下载文件,它们似乎已损坏。

var fileUrl = 'http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=5'; //for example
Meteor.http.call("GET", fileUrl, function funcStoreFile(error, result) {
    "use strict";
    if (!error) {
        var fstream = Npm.require('fs'),
            filename = './.meteor/public/storage/' + collectionId;

        fstream.writeFile(filename, result.content, function funcStoreFileWriteFS(err) {
            if (!err) {
                var Fiber = Npm.require('fibers');
                Fiber(function funcStoreImageSaveDb() {
                    MyfileCollection.update({_id: collectionId}, {$set: {fileFsPath: filename}});
                }).run();
            } else {
                console.log('error during writing file', err);
            }
        });
    } else {
        console.log('dl file FAIL');
    }
});

我做了一个从 public/storage 到 ../.meteor/public/storage 的符号链接,以启用从 url 直接下载(http://localhost:3000/storage/myfileId

当我比较用这个系统下载的文件和直接从浏览器下载的相同文件时,它们是不同的。我的观念有什么问题?

4

1 回答 1

2

我有一个类似的问题,并根据这个讨论提出了解决方案: 在 https://github.com/meteor/meteor/issues/905

通过使用流星也在后台使用的请求库,可以避免二进制下载的问题。此外,我建议不要将小文件保存到文件系统,而是直接在 mongodb 中编码的 base64。如果您计划部署到meteor.com 或其他云服务,这是最简单的解决方案。我在开发中将文件保存到公共目录时发现的另一个故障是,meteor 正在为公共目录中的每次更改重新加载文件。这可能会在下载文件块时导致数据损坏。这是我根据上述讨论使用的一些代码。

Future = Npm.require("fibers/future")
request = Npm.require 'request'    
Meteor.methods
      downloadImage: (url) ->
        if url
          fut = new Future()
          options =
              url: url
              encoding: null
          # Get raw image binaries
          request.get options, (error, result, body) ->
              if error then return console.error error
              base64prefix = "data:" + result.headers["content-type"] + ";base64,"
              image = base64prefix + body.toString("base64")
              fut.ret image
          # pause until binaries are fully loaded
          return fut.wait()
        else false

Meteor.call 'downloadImage', url, (err, res) ->
  if res
    Movies.update({_id: id}, {$set: {image: res}})

希望这会有所帮助。

于 2013-05-24T14:42:03.463 回答