很多時候網站中都會有下載功能,一般的下載直接指定a鏈接然后直接就能下載了,但是有些文件比較特殊,如圖片,指定a鏈接的時候會直接在瀏覽器中打開圖片,這並不是我們想要的,有人說在a鏈接中加個download屬性,其實這個方法在低版本的google瀏覽器中是可以實現的,但是在高版本的瀏覽器中是沒法實現的。說了這么多具體怎么將圖片作為附件下載下來,請看下面的代碼
function downloadImage(path,imgName) { var _OBJECT_URL; var request = new XMLHttpRequest(); request.addEventListener('readystatechange', function (e) { if (request.readyState == 4) { _OBJECT_URL = URL.createObjectURL(request.response); var $a = $("<a></a>").attr("href", _OBJECT_URL).attr("download", imgName); $a[0].click(); } }); request.responseType = 'blob'; request.open('get', path); request.send(); }
第一個參數為圖片的地址,第二個參數為下載后圖片的名稱
但以上方法只限於下載圖片,如果需要下載其它附件如pdf,txt等需要使用以下方法(我用的是webservice)
[WebMethod(Description = "下載文件")] public void GetDldFile(string url) { FileInfo file = new FileInfo(HttpRuntime.AppDomainAppPath + url); if (file.Exists) { HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString()); HttpContext.Current.Response.ContentType = "text/plain"; HttpContext.Current.Response.TransmitFile(file.FullName); HttpContext.Current.Response.End(); } }
前台js這樣寫
var url = "http://192.168.0.1/PatrolStatisticsForRService.asmx/GetDldFile"; window.open(encodeURI(url + '?url=123.txt'));