JS通过ajax 下载文件流

服务端

 var ms = new MemoryStream();
//multipart为文件流
                multipart.CopyTo(ms);
                ms.Position = 0;
                byte[] bytes = ms.ToArray();
//ContentType 为文件类型 Name 为文件名
                return new JsonResult(new Result()
                {
                    Code = 200,
                    Data = new { Stream = bytes, ContentType = "application/vnd.ms-excel", Name =  Name }
                });

js 

//将base64转为Blob
bs64toBlob : function (bs64Data, contentType, sliceSize){
                    contentType = contentType || ''
                    sliceSize = sliceSize || 512

                    var byteCharacters = window.atob(bs64Data)//WindowOrWorkerGlobalScope.atob() 对用base-64编码过的字符串进行解码,基本兼容所有浏览器
                    var byteArrays = []

                    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                        var slice = byteCharacters.slice(offset, offset + sliceSize)

                        var byteNumbers = new Array(slice.length)
                        for (var i = 0; i < slice.length; i++) {
                            byteNumbers[i] = slice.charCodeAt(i)
                        }

                        var byteArray = new Uint8Array(byteNumbers)

                        byteArrays.push(byteArray)
                    }

                    var blob = new Blob(byteArrays, { type: contentType })
                    return blob
                },

download(url, name) {
                    $.ajax({
                        type: 'Get',
                        url: "url",    //规定连同请求发送到服务器的数据;
                        contentType: "application/octet-stream;",
                        success: function (result) {
                            if (result.Code == 200) {
                                // 创建隐藏的可下载链接
                                var eleLink = document.createElement('a');
                                eleLink.download = result.Data.Name;
                                eleLink.style.display = 'none';
                                // 字符内容转变成blob地址
                                var blob = bs64toBlob(result.Data.Stream, result.Data.ContentType);
                                eleLink.href = URL.createObjectURL(blob);
                                // 触发点击
                                document.body.appendChild(eleLink);
                                eleLink.click();
                                // 然后移除
                                document.body.removeChild(eleLink);
                            } else {
                                //错误提示
                            }

                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            
                        }
                    })
                }

 

你可能感兴趣的:(JS通过ajax 下载文件流)