gpt4 book ai didi

angular - 使用 angular 2 和 web API 下载文件

转载 作者:太空狗 更新时间:2023-10-29 17:57:02 25 4
gpt4 key购买 nike

我有 Angular 4 和 Web API 应用程序,我正在尝试使用 Web API 和 typescript Blob 下载文件。下面是两者的代码示例。当我点击下载按钮时,一个发布请求被发送到 web API 作为响应发送文件流, typescript 将这个流转换为图像。但是当我打开这张图片时,它会显示以下错误 - “我们无法打开此文件”。

代码-:网络接口(interface)

    public HttpResponseMessage Download()
{
string strFileUrl = "some absolute path";

if (strFileUrl != "")
{
FileInfo file = new FileInfo(strFileUrl);

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);


var stream = new FileStream(file.FullName, FileMode.Open);
response.Content = new StreamContent(stream);
// response.Content = new ByteArrayContent(CommonUtil.FileToByteArray(file.FullName));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(CommonUtil.GetContentType(file.Extension.ToLower()));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = file.Name
};
response.Content.Headers.ContentDisposition.FileName = file.Name;
response.Content.Headers.ContentLength = file.Length;
response.Headers.Add("fileName", file.Name);

return response;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}

Angular 组件.ts -

private OnImageDownloadClick()
{
this.uploadServiceRef.DownloadFile(path).subscribe(x => {

// method 1
let head = x.headers.get("Content-Type");
let fileName = x.headers.get("fileName");
this.fileSaverServiceRef.save(x, fileName, head);

OR

// method 2
let head = x.headers.get("Content-Type");
var blob = new Blob([x.arrayBuffer], { type: head });

var fileURL = URL.createObjectURL(blob);
window.open(fileURL);
},
error => console.log(error));
}

服务.ts-

public DownloadFile(path): Observable<any> {
let obj: any = {
path: path
}
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('responseType', ResponseContentType.Blob);

return this.http.request(DOWNLOAD_DOCUMENT_URL, RequestMethod.Post, this.headers, obj)
.map((x) => {
return x;
});
}

最佳答案

我在从流创建 docx 文件时遇到了类似的问题,我最终这样做了:

服务.ts:

postAndGetResponse(myParams){
return this._http.post(this.api, {myParams}, {responseType: ResponseContentType.Blob})
.map(response => (<Response>response).blob())
.catch(this.handleError);
}

组件.ts:

downloadFile(){
this.service.postAndGetResponse(myParams).subscribe(response => {
var fileName = "nameForFile" + ".extension";
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(response, fileName);
}else{
var link = document.createElement('a');
link.setAttribute("type", "hidden");
link.download = fileName;
link.href = window.URL.createObjectURL(response);
document.body.appendChild(link);
link.click();
}
});
}

关于angular - 使用 angular 2 和 web API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45461410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com