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)中的方式,將文件名以參數的形式傳到后台,后台找到文件通過流的形式下載文件即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM