简单的问题
我有一个来自 Google Drive API 的缩略图,我需要保存一份副本,因为它有有效期。
语境
我正在为管理员构建一个后端以向网站添加内容,并且我使用 Google Drive 作为资源管理工具。我在 Meteor 上运行它,所以它是服务器端的 Nodejs。
尝试
使用众所周知的canvas方法来检索数据url
getImageDataURL = function (URL, cb) { var img = document.createElement("img"); var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); img.setAttribute('crossorigin','anonymous'); img.onload = function () { canvas.width = this.width; canvas.height = this.height; ctx.drawImage(img, 0, 0); cb && cb(canvas.toDataURL("image/jpg")); }; img.src = URL; };
但由于 CORS 限制(缩略图来自 Google 域),它失败了。
"Okay, so since it'll be stored on the server, I might as well do the job directly there."
好吧,可以获取图像内容,但是由于一些未知的黑暗诅咒,我没有设法将内容转换为正确的 base64 格式。生成的字符串几乎与预期的输出相似,但有大约 10% 的不匹配字符......我尝试了大量的函数来进行 base64 转换,但我无法正确处理。我最终得到了这个我认为是正确的简单代码女巫,内容编码肯定缺少一些东西......(这是流星代码,使用 collection-hooks 包)Medias.before.insert(function (userId, doc) { var res = HTTP.get(doc.thumb); doc.thumb = "data:"+res.headers["content-type"]+";base64,"+new Buffer(res.content, 'ascii').toString('base64'); });
我尝试了使用和不使用缓冲区包装器以及所有可能的缓冲区编码参数,与其他传统转换函数相比,'ascii' 是产生正确输出的原因,例如:http://hellerim.net/base64_src.php。
"Proxy the god damn image then!"
是的,尝试过,遇到了 html 标头的问题...(http-methods 包)HTTP.methods({ '/getImage/:url': function(){ var req = HTTP.get(this.params.url); this.addHeader('access-control-allow-origin', '*'); this.addHeader('content-disposition', req.headers['content-disposition']); this.addHeader('content-type', req.headers['content-type']); //this.addHeader('content-length', req.headers['content-length']); return req.content; } });
如果我不设置“内容类型”,我会得到数据,当然是文本。否则我什么也得不到。
"Right, this is because 'content-length' is missing!"
...如果我添加它,我的服务器会因可爱的错误而崩溃Can't render headers after they are sent to the client
。我又一次停在这里,因为我不是流星专家,我不知道桌子底下发生了什么。必须有一些自动添加的标题,我必须通过任意定义内容长度来搞乱一些过程,否则我不知道,见鬼!"Wow, dude, you like it hard! Why don't you just store them as files?"
首先,我更喜欢将其存储到数据库中,因为它更易于管理,而且我相信使用 dataURL 最适合快速显示缩略图。其次,因为禁止访问流星公共文件夹,所以我必须手动将文件存储到服务器上的其他地方,女巫很丑,然后提供一个访问点来允许他们检索,真是一团糟。另外我尝试了mongodb的gridfs文件存储。无法让它工作,meteor 包装器(CollectionFS 包)太有问题了,它有很多用于简单存储缩略图的基础设施。
所以,如果有人对第一点有任何想法,我马上给他买啤酒!我已经坚持了一个多星期了,我的弹药用完了!
谢谢 =)