.net core部署linux下载文件 文件为中文下载

在项目中,需要下载模板,某个文件夹下有excel文件或者word等  文件名为中文的时候在linux服务器下载不了  

如果直接写路由的话在windows下是可以直接访问的,但是core部署在linux上 所以会有些不同

第一种:写一个接口使用流下载

[httpget("download")]

public async Task<FileResult>  DownLoad()

{

  var filePath = System.IO.Path.Path.Join(System.IO.Path.GetDirectoryName(typeof(Program).Assembly.Location),"UpLoad","文件名。xlsx");

         return File(System.IO.File.ReadAllBytes(filePath),"application/octet-stream;charset=utf-8",System.IO.Path.GetFileName(filePath));

return null;

}

 

第二种:使用中间件,写一个解码中间件,然后把文件路径给前端,拼接上端口使用 windos.open 可直接下载

首先先写一个中间件类

public class UrlDecodeMiddleware

{

  private readonly RequestDelegate _next;

      public UrlDecodeMiddleware(RequestDelegate)

      {

  _next=next;

      }

     public async Task Invoke(HttpContext context)

 {

  if(context.Request.Method="Get")

  {

      context.Request.QueryString= new QueryString(HttpUtility.UrlDecode(context.Request.QueryString.Value));

      }

  await _next(context);

    }

}

///拓展方法将中间件加入到请求处理通道中

public static class UrlDecodeMiddlewateExtensions

{

  public static IapplicationBuilder UserUrlDecode(this IApplicationBuilder app)

  {

    return app.UserMiddleware<UrlDecodeMiddleware>();

  }

}

最后在Startup中的Configure中使用

app.UseUrlDecode();  就可以了

posted @ 2024-07-09 16:11  Best丶zhaotf  阅读(1)  评论(0编辑  收藏  举报