【问题标题】:Set The Name of a ZipArchive Zip File In Web API在 Web API 中设置 ZipArchive Zip 文件的名称
【发布时间】:2019-03-14 11:52:36
【问题描述】:

我似乎无法从 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


    【解决方案1】:

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

    【讨论】:

    • 这似乎是一种解决方法,但如果 Web API 不允许在 HttpResponseMessage 中设置 zip 文件名,这可能是一种解决方案。
    • @Jnr 尝试添加标头 responseMessage.Content.Headers.Add("x-filename", attachmentName);
    • 还将 responseType: ResponseContentType.ArrayBuffer 更改为 ResponseContentType.Blob
    • 这两个都试过了,都没用。
    【解决方案2】:

    我仍然不完全确定为什么不使用 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);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2016-09-28
        • 2023-04-07
        • 1970-01-01
        • 2018-07-13
        • 1970-01-01
        • 2016-03-08
        • 2012-08-22
        • 1970-01-01
        • 2016-08-26
        相关资源
        最近更新 更多