在Web API中设置ZipArchive Zip文件的名称

问题描述 投票:1回答:3

我似乎无法从HttpResponseMessage中的Web API设置zip文件的名称。我可以使用ZipArchive及其所有内容文件成功创建zip文件,但是当从客户端下载它时(虽然它确实返回并成功打开),该名称以16字节十六进制格式出现,如guid。我想为我的zip文件设置一个自定义名称。我应该在哪里这样做?

设置ContentDisposition不起作用:

responseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
     FileName = attachmentName
};

从客户端使用Angular2 +我将文件作为blob返回:

DownloadAtachment(url: string): Observable<Blob> { 
 const requestHeaders = new Headers(
    {
        'Content-Type', 'application/json',
        'Accept', 'application/zip'
    },
 );

 let options = new RequestOptions({ headers: requestHeaders });
 let args: RequestOptionsArgs = {headers: options, withCredentials:false, responseType: ResponseContentType.ArrayBuffer};

 return this._http.get(url, args)
    .map(response => {
        return new Blob([response.blob()], { type: 'application/zip'});
    });
}
c# angular asp.net-web-api2 ziparchive httpresponsemessage
3个回答
1
投票

我建议使用file-saver js库(检查Angular 2 Best approach to use FileSaver.js)或ngx-filesaver,更多信息在这里https://www.npmjs.com/package/ngx-filesaver


1
投票

我仍然不完全确定为什么不使用HttpResponseMessage标头,但我只是使用不同的方式来处理响应。因此,而不是使用以下来打开blob:

const fileurl = URL.createObjectURL(res);
window.open(fileurl, '_self');

我使用@ViewChild访问隐形锚标签来处理点击并设置附件名称:

const fileurl = URL.createObjectURL(res);
const link = this.zipClick.nativeElement as HTMLAnchorElement;
link.href = fileurl;
link.donwload = "Name.zip";
link.click();
window.URL.revokeObjectURL(fileurl);

0
投票

如果您不需要使用Angular的HttpClient下载它,您可以在模板中简单地创建一个<a [href]="url" target="_blank">Download zip</a>。它也许有效。

© www.soinside.com 2019 - 2024. All rights reserved.