我有一个dotnet核心api,它返回一个FileContentResult ..
return new FileContentResult(bytes, contentType)
{
FileDownloadName = Path.GetFileName(request.Filename)
};
通过邮递员,我可以完美地读出图像。现在我想通过aurelia fetch客户端读取图像,并在我的html视图中显示它。这是我从api中检索图像的功能。
public image(filename: string) {
return this.http.fetch(AppConfiguration.base_url + 'assets/image',
{
method: 'post',
body: json({
filename: filename
})
});
}
我尝试使用此值转换器转换响应中的blob。但我无法让它工作
转换器:
export class BlobToUrlValueConverter {
public toView(blob) {
return URL.createObjectURL(blob);
}
}
视图模型:
export class Dashboard {
public blob: any;
constructor(
public assets_service: AssetsService
) { }
async attached() {
let response = await this.assets_service.image('test.png');
this.blob = response.blob();
}
}
查看
<div if.bind="blob">
${ blob | blobToUrl }
</div>
我不确定这是正确的做法。也不确定如何处理它的异步请求部分。在html视图中显示图像响应的最佳方法是什么?让我们说通过img标签?
答案 0 :(得分:4)
我很亲密。这是我如何显示图像。
视图模型:
export class Dashboard {
public url: string;
constructor(
public assets_service: AssetsService
) { }
async attached() {
let blob = await this.assets_service.image('test.png')
.then(response => response.blob());
this.url = URL.createObjectURL(blob);
}
}
查看:
<div if.bind="url">
<img src.bind="url">
</div>
修改强>
使用上面写的部分找到了更好的解决方案:
执行调用的导出函数(对于ts和html端的可重用性):
export function image_request(filename: string): Promise<Response> {
let http = new Http();
return http.fetch(<your-url-that-fetches-the-image>,
{
method: 'post',
body: json({
filename: filename
})
});
}
使用上述功能的值转换器
import { image_request } from './AssetsRequests';
export class ImageRequestValueConverter {
public toView(filename: string) {
return image_request(filename);
}
}
解决方案中重要且最棒的部分。非常感谢http://www.sobell.net/aurelia-async-bindings/ 让我在路上。您可以覆盖绑定行为。您可以使用此覆盖来处理异步 在视图中与价值转换器结合使用。
export class AsyncImageBindingBehavior {
public bind(binding, source): void {
binding.originalupdateTarget = binding.updateTarget;
binding.updateTarget = (target) => {
// When we have a promise
if (typeof target.then === 'function') {
// Set temp value to loading so we know its loading
binding.originalupdateTarget('Loading...');
// Process the promise
target
.then(response => response.blob())
.then(blob => binding.originalupdateTarget(
URL.createObjectURL(blob)
));
}
else {
binding.originalupdateTarget(target);
}
};
}
unbind(binding) {
binding.updateTarget = binding.originalupdateTarget;
binding.originalupdateTarget = null;
}
}
最后视图很简单
<img src="${ 'test.png' | imageRequest & asyncImage }">