如何使用Vue.js下载在.NET Core控制器方法中设置的具有特定名称的文件?

问题描述

我已经定义了一个端点,该端点将文件返回到我的前端项目。端点如下所示:

[HttpGet("{shipmentId:int}/pod")]
public async Task<IActionResult> GetShipmentPodAsync([FromRoute] int shipmentId)
{
   try
   {
      var result = await QueryBus
                    .SendAsync<GetShipmentPodQuery,PodFile>(
                        new GetShipmentPodQuery
                        {
                           ShipmentId = shipmentId
                        });

      return File(result.Content,result.Type,result.FileName);
   }
   catch (Exception e)
   {
      // ToDo: Handle exception in proper way
      return StatusCode(StatusCodes.Status500InternalServerError,e.Message);
   }
}

以下功能负责与提到的端点进行通信:

  async getPodFile(shipmentId) {
    const resource = `shipment/${shipmentId}/pod`;
    await client.getFile(resource)
      .then((result) => {
        const fileUrl = window.URL.createObjectURL(new Blob([result.data]));
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        a.href = fileUrl;
        a.download = `test.pdf`;
        a.click();
        window.URL.revokeObjectURL(fileUrl);
        document.body.removeChild(a);
      });
  },

我想使用从我的API返回的文件名,但是在接收到响应后我不知道如何访问它(我试图记录响应对象,但未找到“文件名”之类的字段)。如何使用从服务器获取的名称而不是硬编码的名称?

解决方法

首先,您需要在API中设置文件名。

例如,您可以在“ content-disposition”标题中执行此操作。 这是一种方法:

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
            {
             Content = new ByteArrayContent(stream.ToArray())
            };

            result.Content.Headers.ContentDisposition =
            new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = recordToDown.Name
            };

在API响应中检查“ content-disposition”标头,它应具有名为“ filename”的属性

,

我找到了解决方案-CORS阻止了包含文件名的标头。我必须将WithExposedHeaders添加到我的CORS配置中:

        private const string ContentDispositionHeaderName = "Content-Disposition";

        internal static IServiceCollection ConfigureResourceSharing(this IServiceCollection services,IConfiguration configuration)
        {
            var originsContainer = configuration
                .GetSection(AllowedOriginsSectionName)
                .Get<ICollection<string>>();

            return services
                .AddCors(o =>
                {
                    o.AddPolicy(PolicyName,b =>
                        {
                            foreach (var origin in originsContainer)
                            {
                                b.WithOrigins(origin)
                                    .WithExposedHeaders(ContentDispositionHeaderName)
                                    .AllowAnyHeader()
                                    .AllowAnyMethod()
                                    .AllowCredentials();
                            }
                        });
                });
        }

添加此行可以解决问题,并且可以从此标头中获取文件名:)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...