在我的 meteor 应用程序中,服务器尝试下载一些文件以将它们存储在文件系统上。 我使用 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 的符号链接(symbolic link),以启用从 url ( http://localhost:3000/storage/myfileId ) 的直接下载
当我比较用这个系统下载的文件和直接从浏览器下载的相同文件时,它们是不同的。我的观念有什么问题吗?
最佳答案
我遇到了类似的问题,并根据此讨论提出了解决方案: on https://github.com/meteor/meteor/issues/905
通过使用 meteor 也在后台使用的请求库,可以避免二进制下载的问题。此外,我建议不要将小文件保存到文件系统,而是直接在 mongodb 中进行 Base64 编码。如果您计划部署到meteor.com 或其他云服务,这是最简单的解决方案。 我在开发中将文件保存到公共(public)目录时发现的另一个问题是,当公共(public)目录中的每次更改时, meteor 都会重新加载文件。当下载文件 block 时,这可能会导致数据损坏。这是我根据上述讨论使用的一些代码。
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}})
希望这对您有所帮助。
关于meteor - [meteor][0.6.*] 使用meteorjs,如何使用Meteor.http下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16710185/