jq实现图片下载功能

很多时候网站中都会有下载功能,一般的下载直接指定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'));
原文地址:https://www.cnblogs.com/dushaojun/p/11364370.html