下载后在客户端获取文件名。 CORS

时间:2017-05-21 15:46:29

标签: c# angular asp.net-core cors asp.net-core-1.0

我设法从服务器端下载文件:

[EnableCors("AllowAll")]
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
    var fileName = "Far30b4949.x86.20170503.zip"; //*** Creation file name
    var filepath = _hostingEnvironment.WebRootPath;
    byte[] fileBytes = System.IO.File.ReadAllBytes(_hostingEnvironment.WebRootPath + 
                          @"\" + fileName);
    return File(fileBytes, "application/zip", fileName); //*** Sending file name
}

和客户端代码:

public downloadFile() {       
    let projectAUrl = 'http://localhost:49591/api/file/5';
    return this.http.get(projectAUrl, {responseType: ResponseContentType.Blob})
        .map((response) => {
            return new Blob([response.blob()], {type:'application/zip'})
        })
        .subscribe((res)=> {
            saveAs(res, "Name does not come here")//there is no file name, 
            //but there is a file type("application/zip")
        });
}

CORS设置:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    //Add CORS support to the service
    services.AddCors(options=> options.AddPolicy("AllowAll", p => 
            p.AllowAnyOrigin()
             .AllowAnyHeader()
             .AllowAnyMethod()
             .AllowCredentials()));
}

我在客户端有什么: enter image description here

但是,从服务器端下载文件时,客户端没有文件名。我怎样才能获得文件名?

更新

我已移除对map()的电话:

public downloadFile() {       
    let projectAUrl = 'http://localhost:49591/api/file/5';
    return this.http.get(projectAUrl, {responseType: ResponseContentType.Blob})            
        .subscribe((res)=> {
            saveAs(res, "Name does not come here")//there is no file name, 
            //but there is a file type("application/zip")
        });
}

但是,没有文件名:

enter image description here

更新2:

如果我对CORS使用以下策略:

services.AddCors(options => options.AddPolicy("ExposeResponseHeaders", 
    p =>
    { 
        p.WithOrigins("http://localhost:49591")
         .WithExposedHeaders("Content-Disposition");
    }));

然后我收到以下错误:

XMLHttpRequest cannot load http://localhost:49591/api/file/5. No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin 
'http://localhost:3000' is therefore not allowed access. The response had 
HTTP status code 500.

2 个答案:

答案 0 :(得分:4)

只需删除对map的调用,并在subscribe lambda函数中提取blob数据和文件名:

public downloadFile() {       
    let projectAUrl = 'http://localhost:49591/api/file/5';
    return this.http.get(projectAUrl, {responseType: ResponseContentType.Blob})
        .subscribe((response)=> {
            var blob = new Blob([response.blob()], {type:'application/zip'});
            var header = response.headers.get('Content-Disposition');
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(header);
            if (matches != null && matches[1]) { 
                fileName = matches[1].replace(/['"]/g, '');
            }
            saveAs(blob, fileName);
        });
}

Content-Disposition标头解析取自: How to get file name from content-disposition

关于您的CORS配置

您可以尝试使用以下策略(添加浏览器无法读取的任何其他标题):

services.AddCors(options => options.AddPolicy("ExposeResponseHeaders", 
    p =>
    { 
        p.WithOrigins("http://localhost:3000") // single origin THIS MUST BE THE SAME OF YOUR ANGULAR APPLICATION (not your ASP.NET Core app address)
         .AllowAnyMethod() // any method
         .AllowAnyHeader() // any header is *allowed*
         .AllowCredentials() // credentials allowed
         .WithExposedHeaders("Content-Disposition"); // content-disposition is *exposed* (and allowed because of AllowAnyHeader)
    }));

答案 1 :(得分:0)

尝试在返回结果之前在Controller中显式添加“ Access-Control-Expose-Headers”。
例如:

[HttpPost("export/excel")]
public async Task<IActionResult> ExportToExcel([FromBody] ExportReportRequest request)
{
    ...
    (byte[] fileContents, string fileName) = await this.salaryService.ExportReportToExcelAsync(request, userId).ConfigureAwait(false);
    this.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
    return this.File(fileContents, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}