window.locatin.href 中特殊字符串问题

(1)使用window.location.href 下载文件时,当参数中有特殊字符(例如:+、空格、=、%、&、#) 等,

 window.location.href = rootUrl + 'ATEWEB_Import/SPECModelList/DownloadSPECListFile?specVersion=' + SPECVersion;

报错:

从客户端(&)中检测到有潜在危险的 Request.Path 值。

文件无法下载。

解决:

参数中特殊字符,对相应参数进行编码即可:

  window.location.href = rootUrl + 'ATEWEB_Import/SPECModelList/DownloadSPECListFile?specVersion=' + encodeURIComponent(SPECVersion);

这样特殊字符,就会被编码,浏览器不会再识别到特殊字符。MVC后台用流的方式下载文件。将文件转成流或者二进制数组进行下载

  public FileResult DownloadSPECListFile(string specVersion)
        {
            SPECList_Rename sPECModelList = _sPECListBusiness.GetIQueryable().Where(q => q.SPECVersion == specVersion).FirstOrDefault();
            string xmlStr = sPECModelList.SPECList;
            string fileName = CreateSPECFile(xmlStr);
            string path = Server.MapPath("~/Download/" + fileName);
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            return File(fs, "application/octet-stream", fileName);
        }

 

(2)window.location.href 直接指向文件

 window.location.href = rootUrl + 'ATEWEB_Import/SPECModelList/ces&spc.xlsx';

这个使用 encodeURI 是不起作用的,因为该方法不会对&等特殊字符串编码。

只能改成(1)中的方式,将文件名以参数的形式传到后台,后台找到文件通过流的形式下载文件即可。

 

posted @ 2020-11-10 19:23  黄树强  阅读(1295)  评论(0编辑  收藏  举报