仅当我将 x-authentication 令牌添加到“GET”http 请求的标头(并且我不想使用 cookie)时,才能提供我的文件。直接后果是我不能仅通过在 html 中使用其 URL 来调用文件,我需要从 JavaScript 调用中获取它,最好是异步的。
由于我的客户是 Meteor,所以我想使用 HTTP.get 方法。我得到了通过 http.get 获取文件的部分,但不是我将其附加到例如图像的 src 属性的部分。
如果我想在我的页面中使用它,我应该如何返回我的文件下载结果?(例如将其附加到图像的 src 属性)。我应该使用专用模板还是可以使用助手来实现?
编辑:我取得了一些进展。基于对类似案例的回答“如何显示使用 XMLHttpReques t 下载的图像,我已经看到您可以在 base64 中编码响应内容文本。
所以这是我的想法:我使用一个助手来返回 img src 属性。我知道当我在客户端使用 http 调用时它是异步的,所以我默认返回一个占位符值(见最后一行)
这是我的代码(在 img src 属性中调用了助手):
link : function(){
HTTP.get ("http://localhost:3000" + Files.baseURL + "/" + this.md5,
{
headers:{
"X-Auth-Token": Accounts._storedLoginToken()
}
},
function (error, result) {
if (error){
console.log ("an error " + result.statusCode + " occured");
}
else
{
retval ="";
for (var i=0; i<=result.content.length-1; i++)
retval += String.fromCharCode(result.content.charCodeAt(i) & 0xff);
return "data:"+this.contentType+";base64," + encode64(retval)
}
})
return "http://localhost:3000/images/placeholder.png"
},
此代码不起作用,它在 http.get 行上引发错误。“模板助手中的异常:.link@ http://localhost:3000/client/views/uploader/uploader.js?b82cf5a1d421ef6a5a1e4eabaf8327fd1a9f2d75:43:2 ”