Jak*_*ner 6 c# asp.net asp.net-mvc angular
我有C#后端和ASP.Net MVC的经验.现在我正在第一次尝试Angular 2.这需要时间,但我喜欢它的大部分内容.现在我被困在一个简单的文件下载上.
我已经阅读了我在Stackoverflow上找到的所有示例,但我仍然没有得到我的例子.
在服务器端,我有这个C#代码:
public ActionResult DownloadPicture(long id)
{
var bytes = System.IO.File.ReadAllBytes("images\dummy.jpg");
return GetAttachement(bytes, "DummyFile.jpg");
}
private ActionResult GetAttachement(byte[] bytes, string fileName)
{
var contentType = MimeMapping.GetMimeMapping(fileName);
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(bytes, contentType);
}
Run Code Online (Sandbox Code Playgroud)
在客户端,我有这个Typescript代码:
public pictureDownload(id: number): void {
let options = new RequestOptions({ search: new URLSearchParams("id=" + id) });
this.http.get(this.urlPictureDownload, options).subscribe((data: any) => {
// var blob = new Blob([data._body], { type: "image/jpeg" });
// var url = window.URL.createObjectURL(blob);
// window.open(url);
});
}
Run Code Online (Sandbox Code Playgroud)
请求进入服务器端.该阵列已下载.我想我的问题在于客户端.谁能帮我吗?
对于所有未来的读者,我在这里总结了一切。根据EsDF的建议和peinearydevelopment的建议,我现在有了一个可行的解决方案。在请求中将responseType指定为ArrayBuffer是最关键的部分,下载技巧确实很有帮助。
Alt 1:我认为凯西是对的。只要有可能,最简单的方法就是使用指向服务器资源的简单链接标记。当像我的情况一样,这不是一个选择时,其他两种选择中的任何一种都会有用。
Alt 2:openPictureInNewWindow 方法是简单直接的方法。缺点是它会显示一个奇怪的网址,如下所示: blob: http://localhost/037713d1-a8b9-4fe3-8c43-ee5998ffdc5d。
Alt 3:另一种方法 downloadFile 将更进一步,创建一个临时链接标记并使用它来下载文件。对于大多数用户来说,这看起来像是正常的方法。但它感觉不像是操纵 DOM 的“Angular 2 方法”,但它是一种对用户更加友好的方法,所以现在我将使用这种方法。感谢所有好的意见!
public pictureDownload(id: number) {
let options = new RequestOptions({ search: new URLSearchParams("id=" + id), responseType: ResponseContentType.ArrayBuffer });
this.http.get(this.urlPictureDownload, options).subscribe((data: any) => {
//this.openPictureInNewWindow(data._body, "image/jpeg");
this.downloadFile(data._body, "Screenshot_" + id + ".jpg", "image/jpeg");
});
}
private openPictureInNewWindow(data: ArrayBuffer, contentType: string) {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
window.open(url);
}
private downloadFile(data: ArrayBuffer, fileName: string, contentType: string) {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Run Code Online (Sandbox Code Playgroud)